fork(1) download
  1. #include <stdio.h>
  2.  
  3. //this gives you the power in a time of O(log N)
  4.  
  5. //for numbers that may go out of range of int...use "long long int" in place of "int"
  6.  
  7. //for understanding the program logic even better you can visit...http://w...content-available-to-author-only...c.com/fast-exponentiation-algorithms/
  8.  
  9. int exp_by_squaring(int n,int pow)//this is a recursive solution...an iterative solution is also possible...!!!
  10. {
  11. if(pow==0)//power is zero
  12. return 1;
  13. if(pow==1)//power is 1
  14. return n;
  15. if(pow&1)//pow is odd
  16. {
  17. int ans=exp_by_squaring(n,pow/2);
  18. return ans*ans*n;
  19. }
  20. //pow is even
  21. int ans=exp_by_squaring(n,pow/2);
  22. return ans*ans;
  23. }
  24. int main(void)
  25. {
  26. printf("%d",exp_by_squaring(2,10));
  27. return 0;
  28. }
Success #stdin #stdout 0s 1832KB
stdin
Standard input is empty
stdout
1024