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.

2,065 total views, 15 views today