spider68

do x^y in log(n)

Apr 3rd, 2020
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.31 KB | None | 0 0
  1. /* Iterative Function to calculate (x^y) in O(log y) */
  2. int power(int x, unsigned int y)
  3. {
  4.     int res = 1;   
  5.     while (y > 0)
  6.     {
  7.         // If y is odd, multiply x with result
  8.         if (y & 1)
  9.             res = res*x;
  10.  
  11.         // y must be even now
  12.         y = y>>1; // y = y/2
  13.         x = x*x; // Change x to x^2
  14.     }
  15.     return res;
  16. }
Add Comment
Please, Sign In to add comment