VOOZH about

URL: https://www.geeksforgeeks.org/dsa/write-an-iterative-olog-y-function-for-powx-y/

⇱ Iterative function for pow(x, y) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Iterative function for pow(x, y)

Last Updated : 2 Apr, 2026

Given two integers x and y, compute xy efficiently. The approach should run in O(log y) time complexity and use O(1) auxiliary space.

Examples:

Input: x = 3, y = 19
Output: 1162261467
Explanation: 319 = 1162261467

Input: x = 2, y = 5
Output: 32
Explanation: 25 = 32

Binary Exponentiation - O(log y) Time and O(1) Space

Instead of multiplying x repeatedly y times, we use the binary representation of y to make the computation faster. Every number can be written as the sum of powers of 2, so we only need to consider those powers where the binary bit is 1.

We traverse through all the bits of y from LSB to MSB.

  • If the current bit is 1, we multiply our answer with x.
  • If the current bit is 0, we ignore it.
  • At every step, we square x (to get the next power) and divide y by 2 to move to the next bit.
👁 lsb_msb

Output
1162261467
Comment
Article Tags: