Write an iterative O(Log y) function for pow(x, y)
Last Updated :
23 Aug, 2024
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 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 <iostream>
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 "<<power(x, y);
return 0;
}
// this code is contributed by shivanisinghss2110
C
// Iterative C++ program to implement pow(x, n)
#include <stdio.h>
/* 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
JavaScript
<script>
// Iterative Javascript program to implement pow(x, n)
/* Iterative Function to calculate (x^y) in O(logy) */
function power(x, y)
{
// Initialize result
let 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 >> 1; // y = y/2
x = x * x; // Change x to x^2
}
return res;
}
// Driver program to test above functions
let x = 3;
y = 5;
document.write("Power is " + power(x, y));
// This code is contributed by Mayank Tyagi
</script>
PHP
<?php
// Iterative php program
// to implement pow(x, n)>
// 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
?>
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 <iostream>
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
Python
#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));
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 log2(n), where log2 denotes the logarithm to the base 2. Therefore, the time complexity of the function is proportional to the number of iterations, which is log2(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).
Similar Reads
Writing power function for large numbers
We have given two numbers x and n which are base and exponent respectively. Write a function to compute x^n where 1 <= x, n <= 10000 and overflow may happenExamples: Input : x = 5, n = 20Output : 95367431640625Input : x = 2, n = 100Output : 1267650600228229401496703205376In the above example,
11 min read
Write you own Power without using multiplication(*) and division(/) operators
Method 1 (Using Nested Loops): We can calculate power by using repeated addition. For example to calculate 5^6. 1) First 5 times add 5, we get 25. (5^2) 2) Then 5 times add 25, we get 125. (5^3) 3) Then 5 times add 125, we get 625 (5^4) 4) Then 5 times add 625, we get 3125 (5^5) 5) Then 5 times add
13 min read
Floor square root without using sqrt() function : Recursive
Given a number N, the task is to find the floor square root of the number N without using the built-in square root function. Floor square root of a number is the greatest whole number which is less than or equal to its square root. Examples: Input: N = 25 Output: 5 Explanation: Square root of 25 = 5
7 min read
Multiplication with a power of 2
Given two numbers x and n, we need to multiply x with 2nExamples : Input : x = 25, n = 3 Output : 200 25 multiplied by 2 raised to power 3 is 200. Input : x = 70, n = 2 Output : 280 A simple solution is to compute n-th power of 2 and then multiply with x. C++ // Simple C/C++ program // to compute x
5 min read
Print all integers that are sum of powers of two given numbers
Given three non-negative integers x, y and bound, the task is to print all the powerful integer ? bound in sorted order. A powerful integer is of the form xi + yj for all i, j ? 0. Examples: Input: x = 3, y = 5, bound = 10 Output: 2 4 6 8 10 30 + 50 = 1 + 1 = 2 30 + 51 = 1 + 5 = 6 31 + 50 = 3 + 1 =
8 min read
Find Cube root of a number using Log function
Given the number N, the task is to find the cube root using the log function.Examples: Input: N = 8 Output: 2.000000Input: N = 27 Output: 3.000000 Approach: To solve the problem mentioned above we will use log() function, according to the following formula: Let cube root of N be d. => ?N = d =
3 min read
Find larger of x^y and y^x
Given two integer numbers, X and Y. find the larger of X^Y and Y^X or determine if they are equal.Examples: Input : 2 3Output : 3^2We know 3^2 = 9 and 2^3 = 8. Input : 2 4Output : Equal A simple solution is to calculate x^y by looping for y times, but if the values of x and y is too large it will ca
4 min read
Find value of y mod (2 raised to power x)
Given two positive integer x and y. we have to find the value of y mod 2x. That is remainder when y is divided by 2x. Examples: Input : x = 3, y = 14 Output : 6 Explanation : 14 % 23 = 14 % 8 = 6. Input : x = 4, y = 14 Output : 14 Explanation : 14 % 24 = 14 % 16 = 14. To solve this question we can u
6 min read
Sum of product of x and y such that floor(n/x) = y
Given a positive integer n. The task is to find the sum of product of x and y such that ?n/x? = y (Integer Division). Examples: Input : n = 5 Output : 21 Following are the possible pairs of (x, y): (1, 5), (2, 2), (3, 1), (4, 1), (5, 1). So, 1*5 + 2*2 + 3*1 + 4*1 + 5*1 = 5 + 4 + 3 + 4 + 5 = 21. Inpu
11 min read
Iterated Logarithm log*(n)
Iterated Logarithm or Log*(n) is the number of times the logarithm function must be iteratively applied before the result is less than or equal to 1. \log ^{*}n:=\begin{cases}0n\leq 1;\\1+\log ^{*}(\log n)n>1\end{cases} Applications: It is used in the analysis of algorithms (Refer Wiki for detail
4 min read