Friday, 2 May 2014

Count pairs such that x^y > y^x

Given a sequence A of N positive integers, write a program to find the number of pairs (A[i], A[j]) such that i < j and A[i]A[j] > A[j]A[i] (A[i] raised to the power A[j] > A[j] raised to the power A[i]).
You are provided with a function named power( ) that takes two positive integers x & y and returns xy. If y is 0, the function returns 1.
The prototype of this function is
int power(int x, int y);
In your program, use this function to count the number of such pairs.

INPUT: Line 1 contains N.
Line 2 contains a sequence of N integers, separated by whitespace.

OUTPUT: A single integer representing the number of required pairs.

CONSTRAINTS: The inputs will satisfy the following properties. It is not necessary to validate the inputs.
1 <= N <= 30
0 <= A[i] <= 8 The input sequence can have repetitions and the count must reflect that.

#include<stdio.h>
int power(int x, int y);
int main()
{
int n,a[30],i,j,count=0;
scanf("%d",&n);
i=0;
while(i<n)
{
scanf("%d",&a[i]);
i++;
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(power(a[i],a[j])>power(a[j],a[i]))
count++;
}
}
printf("%d",count);
return 0;
}
int power(int x, int y)
{
int result = x;
if(y == 0)
return 1;
if(x < 0 || y < 0)
return 0;
for(int i = 1; i < y; ++i)
result *= x;
return result;
}

No comments: