Sunday, July 8, 2007

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

There are again different methods to do this in C

Brute force C program


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



Divide and Conquer C program


#include < stdio.h >
int main(int argc, char*argv[])
{
printf("\n[%d]\n",pow(5,4));
}

int pow(int x, int n)
{
if(n==0)return(1);
else if(n%2==0)
{
return(pow(x,n/2)*pow(x,(n/2)));
}
else
{
return(x*pow(x,n/2)*pow(x,(n/2)));
}
}



Also, the code above can be optimized still by calculating pow(z, (n/2)) only one time (instead of twice) and using its value in the two return() expressions above.

3 comments:

Andrés said...

The first form fails with x^0. It should return 1.

subburajr said...

int
power(int val,int pow)
{
return (pow)?(power(val,pow-1)*val):1;
}

Admin said...

in the second method you are calculating same value again pow(x,n/2)*pow(x,n/2).try to improve it and store it in some variable rather than recalculating it.