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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//Divide and Conquer C program #include <stdio.h> //compiled on gcc 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 ) ) ) ; } } int main( int argc , char *argv[] ) { printf("\n[%d]\n",pow(5,4)); } |

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,340 total views, 5 views today