fork(1) download
  1. #include <stdio.h>
  2.  
  3. // Iterative solution to calculate pow(x, n) using
  4. // binary operators
  5. int power(int x, unsigned n)
  6. {
  7. // initialize result by 1
  8. int pow = 1;
  9.  
  10. // do till n is not zero
  11. while (n)
  12. {
  13. // if n is odd, multiply result by x
  14. if (n & 1)
  15. pow *= x;
  16.  
  17. // divide n by 2
  18. n = n >> 1;
  19.  
  20. // multiply x by itself
  21. x = x * x;
  22. }
  23.  
  24. // return result
  25. return pow;
  26. }
  27.  
  28. // main function
  29. int main(void)
  30. {
  31. int x = -2;
  32. unsigned n = 10;
  33.  
  34. printf("pow(%d,%d) = %d", x, n, power(x, n));
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0s 4536KB
stdin
Standard input is empty
stdout
pow(-2,10) = 1024