Wednesday, January 18, 2012

C Program to Calculate pow(x,n)

Write brute force ,recursion and divide and conquer approach to get pow(x,n) in?

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

Modified Recursion with Min. Number of multiplications:

  double power(double x, unsigned int n)
{
   if (!n) return 1.0;
   if (n == 1) return x;
   double result = power(x, n/2);
   result *= result;
   return (n&1) ? result*x : result;
}

Divide and conquer

#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)));
  }
}  

No comments:

Post a Comment