Open In App
Related Articles

# Write an iterative O(Log y) function for pow(x, y)

Given an integer x and a positive number y, write a function that computes xy under following conditions.
a) Time complexity of the function should be O(Log y)
b) Extra Space is O(1)

Examples:

```Input: x = 3, y = 5
Output: 243

Input: x = 2, y = 5
Output: 32
```

## We strongly recommend that you click here and practice it, before moving on to the solution.

We have discussed recursive O(Log y) solution for power. The recursive solutions are generally not preferred as they require space on call stack and they involve function call overhead.

Following is implementation to compute xy.

## C++

 `// Iterative C program to implement pow(x, n)``#include ``using` `namespace` `std;` `/* Iterative Function to calculate (x^y) in O(logy) */``int` `power(``int` `x, unsigned ``int` `y)``{``    ``int` `res = 1; ``// Initialize result` `    ``while` `(y > 0) {``        ``// If y is odd, multiply x with result``        ``if` `(y & 1)``            ``res = res * x;` `        ``// y must be even now``        ``y = y >> 1; ``// y = y/2``        ``x = x * x; ``// Change x to x^2``    ``}``    ``return` `res;``}` `// Driver program to test above functions``int` `main()``{``    ``int` `x = 3;``    ``unsigned ``int` `y = 5;` `    ``cout<<``"Power is "``<

## C

 `// Iterative C++ program to implement pow(x, n)``#include ` `/* Iterative Function to calculate (x^y) in O(logy) */``int` `power(``int` `x, unsigned ``int` `y)``{``    ``int` `res = 1; ``// Initialize result` `    ``while` `(y > 0) {``        ``// If y is odd, multiply x with result``        ``if` `(y & 1)``            ``res = res * x;` `        ``// y must be even now``        ``y = y >> 1; ``// y = y/2``        ``x = x * x; ``// Change x to x^2``    ``}``    ``return` `res;``}` `// Driver program to test above functions``int` `main()``{``    ``int` `x = 3;``    ``unsigned ``int` `y = 5;` `    ``printf``(``"Power is %d"``, power(x, y));` `    ``return` `0;``}`

## Java

 `// Iterative Java program``// to implement pow(x, n)``import` `java.io.*;` `class` `GFG``{``    ` `/* Iterative Function to``calculate (x^y) in O(logy) */``static` `int` `power(``int` `x, ``int` `y)``{``    ``// Initialize result``    ``int` `res = ``1``;` `    ``while` `(y > ``0``)``    ``{``        ``// If y is odd,``        ``// multiply``        ``// x with result``        ``if` `((y & ``1``) == ``1``)``            ``res = res * x;` `        ``// y must be even now``        ``y = y >> ``1``; ``// y = y/2``        ``x = x * x; ``// Change x to x^2``    ``}``    ``return` `res;``}` `// Driver Code``public` `static` `void` `main (String[] args)``{``    ``int` `x = ``3``;``    ``int` `y = ``5``;` `    ``System.out.println(``"Power is "` `+``                        ``power(x, y));``}``}` `// This code is contributed``// by aj_36`

## Python3

 `# Iterative Python3 program``# to implement pow(x, n)` `# Iterative Function to``# calculate (x^y) in O(logy)``def` `power(x, y):` `    ``# Initialize result``    ``res ``=` `1``    ` `    ``while` `(y > ``0``):``        ` `        ``# If y is odd, multiply``        ``# x with result``        ``if` `((y & ``1``) ``=``=` `1``) :``            ``res ``=` `res ``*` `x` `        ``# y must be even``        ``# now y = y/2``        ``y ``=` `y >> ``1``        ` `        ``# Change x to x^2``        ``x ``=` `x ``*` `x``    ` `    ``return` `res`  `# Driver Code``x ``=` `3``y ``=` `5` `print``(``"Power is "``,``       ``power(x, y))` `# This code is contributed``# by ihritik`

## C#

 `// Iterative C# program``// to implement pow(x, n)``using` `System;` `class` `GFG``{``    ` `/* Iterative Function to``calculate (x^y) in O(logy) */``static` `int` `power(``int` `x, ``int` `y)``{``    ``int` `res = 1; ``// Initialize result` `    ``while` `(y > 0)``    ``{``        ``// If y is odd, multiply``        ``// x with result``        ``if` `((y & 1) == 1)``            ``res = res * x;` `        ``// y must be even now``        ``y = y >> 1; ``// y = y/2``        ``x = x * x; ``// Change x to x^2``    ``}``    ``return` `res;``}` `// Driver Code``static` `public` `void` `Main ()``{``int` `x = 3;``int` `y = 5;` `Console.WriteLine(``"Power is "``+``                   ``power(x, y));``}``}` `// This code is contributed``// by aj_36`

## PHP

 `` `// Iterative Function to``// calculate (x^y) in O(logy)` `function` `power(``\$x``, ``\$y``)``{``    ` `    ``// Initialize result``    ``\$res` `= 1;    ` `    ``while` `(``\$y` `> 0)``    ``{``        ` `        ``// If y is odd, multiply``        ``// x with result``        ``if` `(``\$y` `& 1)``            ``\$res` `= ``\$res` `* ``\$x``;` `        ``// y must be even now``        ` `        ``// y = y/2``        ``\$y` `= ``\$y` `>> 1;``        ` `        ``// Change x to x^2``        ``\$x` `= ``\$x` `* ``\$x``;``    ``}``    ``return` `\$res``;``}` `    ``// Driver Code``    ``\$x` `= 3;``    ``\$y` `= 5;` `    ``echo` `"Power is "``, power(``\$x``, ``\$y``);` `// This code is contributed by ajit``?>`

## Javascript

 ``

Output

`Power is 243`

Time Complexity: O(log y), since in loop each time the value of y decreases by half it’s current value.
Auxiliary Space: O(1), since no extra space has been taken.

#### Another approach:

Step 1: Start the function with the base and exponent as input parameters.
Step 2: Check if the exponent is equal to zero, return 1.
Step 3: Recursively call the function with the base and the exponent divided by 2.
Step 4: If the exponent is even, return the square of the result obtained from the recursive call.
Step 5: If the exponent is odd, return the product of the base, the square of the result obtained from the recursive call, and the base again.

## C++

 `#include ``using` `namespace` `std;` `// Recursive Function to calculate (x^y) in O(logy)``int` `power(``int` `x, ``int` `y)``{``    ``if` `(y == 0)``        ``return` `1;` `    ``int` `temp = power(x, y / 2);``    ``if` `(y % 2 == 0)``        ``return` `temp * temp;``    ``else``        ``return` `x * temp * temp;``}` `// Driver program to test above functions``int` `main()``{``    ``int` `x = 3;``    ``int` `y = 5;` `    ``cout << ``"Power is "` `<< power(x, y);` `    ``return` `0;``}`

## Java

 `/*package whatever //do not write package name here */` `import` `java.io.*;` `class` `GFG {``    ``public` `static` `void` `main(String[] args)``    ``{``           ``int` `x=``3``;``          ``int` `y=``5``;``          ` `          ``System.out.println(``"Power is: "``+power(x,y));``      ` `    ``}``    ``public` `static` `int` `power(``int` `x, ``int` `y)``    ``{``        ``if` `(y == ``0``)``        ``{``            ``return` `1``;``        ``}` `        ``int` `temp = power(x, y / ``2``);``          ``// if y is even``        ``if` `(y % ``2` `== ``0``)``        ``{``            ``return` `temp * temp;``        ``}``        ``else``        ``{``            ``return` `x * temp * temp;``        ``}``    ``}``}``//This code is contributed by aeroabrar_31`

## Python3

 `#python code to demonstrate the above approach``def` `power(x, y):``    ``if` `y``=``=``0``:``        ``return` `1` `    ``temp ``=` `power(x, y ``/``/` `2``)``    ``# if y is even``    ``if` `y ``%` `2` `=``=` `0``:``        ``return` `temp ``*` `temp``    ``else``:``        ``return` `x ``*` `temp ``*` `temp`  `def` `main():``    ``x ``=` `3``    ``y ``=` `5` `    ``print``(``"Power is : "``, power(x,y))`  `main()`

## C#

 `using` `System;` `class` `GFG {``    ``// Recursive Function to calculate (x^y) in O(logy)``    ``static` `int` `power(``int` `x, ``int` `y)``    ``{``        ``if` `(y == 0)``            ``return` `1;` `        ``int` `temp = power(x, y / 2);``        ``if` `(y % 2 == 0)``            ``return` `temp * temp;``        ``else``            ``return` `x * temp * temp;``    ``}` `    ``// Driver program to test above functions``    ``static` `void` `Main()``    ``{``        ``int` `x = 3;``        ``int` `y = 5;` `        ``Console.WriteLine(``"Power is "` `+ power(x, y));``    ``}``}`

## Javascript

 `function` `power(x, y) {``    ``if` `(y == 0)``        ``return` `1;` `    ``let temp = power(x, Math.floor(y / 2));``    ``if` `(y % 2 == 0)``        ``return` `temp * temp;``    ``else``        ``return` `x * temp * temp;``}` `let x = 3;``let y = 5;` `console.log(``"Power is "` `+ power(x, y));`

Output

`Power is 243 `

#### Complexity Analysis:

The time complexity of the power function implemented using recursion is O(log n), where n is the value of the exponent.

In this implementation, the function repeatedly divides the exponent by 2 and squares the base until the exponent becomes zero. The number of iterations required to reach the base case is log₂(n), where log₂ denotes the logarithm to the base 2. Therefore, the time complexity of the function is proportional to the number of iterations, which is log₂(n).

This approach reduces the number of multiplications needed to calculate the result and improves the performance of the function compared to the naive iterative approach, which has a time complexity of O(n).

However, the space complexity of the recursive implementation is also O(log n), since each recursive call adds a new stack frame to the call stack until the base case is reached. Therefore, the space required by the function grows logarithmically with the size of the input. This can become a concern for very large values of n, as it may lead to a stack overflow error.

In summary, the recursive implementation of the power function has a time complexity of O(log n) and a space complexity of O(log n).