fork(2) download
  1. #include <stdio.h>
  2.  
  3. // Optimized recursive solution to calculate pow(x, n)
  4. // using divide and conquer
  5. int power(int x, unsigned n)
  6. {
  7. // base condition
  8. if (n == 0)
  9. return 1;
  10.  
  11. // calculate sub-problem recursively
  12. int pow = power(x, n / 2);
  13.  
  14. if (n & 1) // if y is odd
  15. return x * pow * pow;
  16.  
  17. // else y is even
  18. return pow * pow;
  19. }
  20.  
  21. // main function
  22. int main(void)
  23. {
  24. int x = -2;
  25. unsigned n = 10;
  26.  
  27. printf("pow(%d,%d) = %d", x, n, power(x, n));
  28.  
  29. return 0;
  30. }
Success #stdin #stdout 0s 4548KB
stdin
Standard input is empty
stdout
pow(-2,10) = 1024