Thursday, December 27, 2007

Write a C program to calculate pow(x,n)

1 comments:

Admin said...

Method 1: brute force

int pow(int x, int y)
{
if(y == 1) return x ;
return x * pow(x, y-1) ;
}

Method 2: Efficient logarithmic time complexity

long pow(long x, long n)
{
long result = 1;
while ( n ) {
if ( n & 1 ) {
result = result * x;
n = n-1;
}
x = x*x;
n = n/2;
}
return result;
}