Advertisement
imashutosh51

Binary Exponentiation or Pow(x,y)

Oct 18th, 2022 (edited)
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. /*
  2. Binary Exponentiation:
  3. eg x=2 , y=10
  4. we can also write it as : x=4 ie. base*base 2*2 and exponent=y/2 ie. 5 ie. overall 4^5
  5. we can also write it as : 4^5=4*(4^4)
  6. we can also write it as : 4*(4^4)=4*(16^2)
  7. we can also write it as : 4*256^1   {256 =16*16}
  8.  
  9. Algo:
  10. Base and exponent
  11. if exponent is divisible by 2 then multiply base with base eg base*base
  12. if exponent is not divisible by 2 then multiply base in some variable eg. ans
  13. for example ans=1,base=5 and exponent=3 so answer is 125 then  ans=1*5,base=5 and
  14. exponent=2(ie. exponent-1) so answer is 1*5*(5^2) =125
  15.  
  16. if exponent>0 ans=x^exponent
  17. if exponenet<0 ans=1/(x^exponent)
  18. so we need to store absolute value of exponenet.But there is one catch,exponent can be integer [-2^31 to 2^31 -1 ]
  19. so we can keep maximum positive value in int variable is 2^31 -1 but exponent value can be -2^31 and it's
  20. abosulte 2^31 can give range overflow so use long long int.
  21. */
  22. class Solution {
  23. public:
  24.     double myPow(double x, int p){
  25.         if(p==0) return 1;
  26.         bool sign=false;
  27.         if(p<0) sign=true;
  28.         long long int y=abs(p);
  29.         double ans=1;
  30.         while(y!=1){
  31.             if(y%2==0){
  32.                 x=x*x;
  33.                 y/=2;
  34.             }
  35.             else{
  36.                 ans*=x;
  37.                 y--;
  38.             }            
  39.         }
  40.         if(sign) return 1/(ans*x);
  41.         else return ans*x;
  42.     }
  43. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement