fork download
  1. #include <stdio.h>
  2.  
  3. float power(float x, int n)
  4. {
  5. float temp;
  6.  
  7. printf("Power %f, %d\n", x, n);
  8.  
  9. if( n == 0)
  10. return 1;
  11. temp = power(x, n/2);
  12.  
  13. printf("%f\n", temp);
  14. if ((n % 2) == 0)
  15. return temp*temp;
  16. else
  17. {
  18. if(n > 0)
  19. return x*temp*temp;
  20. else
  21. return (temp * temp) / x;
  22. }
  23. }
  24.  
  25. int main()
  26. {
  27. float res = power(2, 4);
  28. printf("Result 2^4 = %f \n\n", res);
  29.  
  30. res = power(2, 3);
  31. printf("Result 2^3 = %f \n\n", res);
  32.  
  33. res = power(2, -2);
  34. printf("Result 2^-2 = %f \n\n", res);
  35.  
  36. res = power(2, -4);
  37. printf("Result 2^-4 = %f \n\n", res);
  38.  
  39. res = power(-2, -3);
  40. printf("Result 2^4 = %f \n\n", res);
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
Power 2.000000, 4
Power 2.000000, 2
Power 2.000000, 1
Power 2.000000, 0
1.000000
2.000000
4.000000
Result 2^4 = 16.000000 

Power 2.000000, 3
Power 2.000000, 1
Power 2.000000, 0
1.000000
2.000000
Result 2^3 = 8.000000 

Power 2.000000, -2
Power 2.000000, -1
Power 2.000000, 0
1.000000
0.500000
Result 2^-2 = 0.250000 

Power 2.000000, -4
Power 2.000000, -2
Power 2.000000, -1
Power 2.000000, 0
1.000000
0.500000
0.250000
Result 2^-4 = 0.062500 

Power -2.000000, -3
Power -2.000000, -1
Power -2.000000, 0
1.000000
-0.500000
Result 2^4 = -0.125000