Home
Questions
Search
Forum
Contact
Guest Book
Polls!
Got a Question?
 
PREV
Programs
NEXT
 
(39 / 301)
 
 



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.


PREV
COMMENTS                                  INDEX                                  PRINT
NEXT



Last updated: November 3, 2005

www.cracktheinterview.com - Your destination for the most common IT interview questions, answers, frequently asked interview questions (FAQ), C Programs, C Datastructures for technical interviews conducted by the top IT companies around the world!