Given two integers x and n, write a function to compute xn. We may assume that x and n are small and overflow doesn’t happen.

Examples :
Input : x = 2, n = 3
Output : 8
Input : x = 7, n = 2
Output : 49
Naive Approach: To solve the problem follow the below idea:
A simple solution to calculate pow(x, n) would multiply x exactly n times. We can do that by using a simple for loop
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long power( int x, unsigned n)
{
long long pow = 1;
for ( int i = 0; i < n; i++) {
pow = pow * x;
}
return pow ;
}
int main( void )
{
int x = 2;
unsigned n = 3;
int result = power(x, n);
cout << result << endl;
return 0;
}
|
Java
import java.io.*;
class Gfg {
public static long power( int x, int n)
{
long pow = 1L;
for ( int i = 0 ; i < n; i++) {
pow = pow * x;
}
return pow;
}
public static void main(String[] args)
{
int x = 2 ;
int n = 3 ;
System.out.println(power(x, n));
}
};
|
Python
def power(x, n):
pow = 1
for i in range (n):
pow = pow * x
return pow
if __name__ = = '__main__' :
x = 2
n = 3
print (power(x, n))
|
C#
using System;
public class Gfg {
static long power( int x, int n)
{
long pow = 1L;
for ( int i = 0; i < n; i++) {
pow = pow * x;
}
return pow;
}
public static void Main(String[] args)
{
int x = 2;
int n = 3;
Console.WriteLine(power(x, n));
}
};
|
Javascript
function power( x, n)
{
let pow = 1;
for (let i = 0; i < n; i++) {
pow = pow * x;
}
return pow;
}
let x = 2;
let n = 3;
let result = power(x, n);
console.log( result );
|
Time Complexity: O(n)
Auxiliary Space: O(1)
pow(x, n) using recursion:
We can use the same approach as above but instead of an iterative loop, we can use recursion for the purpose.
C++
#include <bits/stdc++.h>
using namespace std;
int power( int x, int n)
{
if (n == 0)
return 1;
if (x == 0)
return 0;
return x * power(x, n - 1);
}
int main()
{
int x = 2;
int n = 3;
cout << (power(x, n));
}
|
C
#include <stdio.h>
int power( int x, int n)
{
if (n == 0)
return 1;
if (x == 0)
return 0;
return x * power(x, n - 1);
}
int main()
{
int x = 2;
int n = 3;
printf ( "%d\n" , power(x, n));
}
|
Java
import java.io.*;
class GFG {
public static int power( int x, int n)
{
if (n == 0 )
return 1 ;
if (x == 0 )
return 0 ;
return x * power(x, n - 1 );
}
public static void main(String[] args)
{
int x = 2 ;
int n = 3 ;
System.out.println(power(x, n));
}
}
|
Python3
def power(x, n):
if (n = = 0 ):
return 1
if (x = = 0 ):
return 0
return x * power(x, n - 1 )
if __name__ = = "__main__" :
x = 2
n = 3
print (power(x, n))
|
C#
using System;
class GFG {
public static int power( int x, int n)
{
if (n == 0)
return 1;
if (x == 0)
return 0;
return x * power(x, n - 1);
}
public static void Main(String[] args)
{
int x = 2;
int n = 3;
Console.WriteLine(power(x, n));
}
}
|
Javascript
<script>
function power(x , n) {
if (n == 0)
return 1;
if (x == 0)
return 0;
return x * power(x, n - 1);
}
var x = 2;
var n = 3;
document.write(power(x, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n) n is the size of the recursion stack
To solve the problem follow the below idea:
The problem can be recursively defined by:
- power(x, n) = power(x, n / 2) * power(x, n / 2); // if n is even
- power(x, n) = x * power(x, n / 2) * power(x, n / 2); // if n is odd
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
class gfg {
public :
int power( int x, unsigned int y)
{
if (y == 0)
return 1;
else if (y % 2 == 0)
return power(x, y / 2) * power(x, y / 2);
else
return x * power(x, y / 2) * power(x, y / 2);
}
};
int main()
{
gfg g;
int x = 2;
unsigned int y = 3;
cout << g.power(x, y);
return 0;
}
|
C
#include <stdio.h>
int power( int x, unsigned int y)
{
if (y == 0)
return 1;
else if (y % 2 == 0)
return power(x, y / 2) * power(x, y / 2);
else
return x * power(x, y / 2) * power(x, y / 2);
}
int main()
{
int x = 2;
unsigned int y = 3;
printf ( "%d" , power(x, y));
return 0;
}
|
Java
class GFG {
static int power( int x, int y)
{
if (y == 0 )
return 1 ;
else if (y % 2 == 0 )
return power(x, y / 2 ) * power(x, y / 2 );
else
return x * power(x, y / 2 ) * power(x, y / 2 );
}
public static void main(String[] args)
{
int x = 2 ;
int y = 3 ;
System.out.printf( "%d" , power(x, y));
}
}
|
Python
def power(x, y):
if (y = = 0 ):
return 1
elif ( int (y % 2 ) = = 0 ):
return (power(x, int (y / 2 )) *
power(x, int (y / 2 )))
else :
return (x * power(x, int (y / 2 )) *
power(x, int (y / 2 )))
if __name__ = = "__main__" :
x = 2
y = 3
print (power(x, y))
|
C#
using System;
public class GFG {
static int power( int x, int y)
{
if (y == 0)
return 1;
else if (y % 2 == 0)
return power(x, y / 2) * power(x, y / 2);
else
return x * power(x, y / 2) * power(x, y / 2);
}
public static void Main()
{
int x = 2;
int y = 3;
Console.Write(power(x, y));
}
}
|
Javascript
<script>
function power(x, y)
{
if (y == 0)
return 1;
else if (y % 2 == 0)
return power(x, parseInt(y / 2, 10)) *
power(x, parseInt(y / 2, 10));
else
return x * power(x, parseInt(y / 2, 10)) *
power(x, parseInt(y / 2, 10));
}
let x = 2;
let y = 3;
document.write(power(x, y));
</script>
|
PHP
<?php
function power( $x , $y )
{
if ( $y == 0)
return 1;
else if ( $y % 2 == 0)
return power( $x , (int) $y / 2) *
power( $x , (int) $y / 2);
else
return $x * power( $x , (int) $y / 2) *
power( $x , (int) $y / 2);
}
$x = 2;
$y = 3;
echo power( $x , $y );
?>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
An Optimized Divide and Conquer Solution:
To solve the problem follow the below idea:
There is a problem with the above solution, the same subproblem is computed twice for each recursive call. We can optimize the above function by computing the solution of the subproblem once only.
Below is the implementation of the above approach:
C++
int power( int x, unsigned int y)
{
int temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else
return x * temp * temp;
}
|
C
int power( int x, unsigned int y)
{
int temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else
return x * temp * temp;
}
|
Java
static int power( int x, int y)
{
int temp;
if (y == 0 )
return 1 ;
temp = power(x, y / 2 );
if (y % 2 == 0 )
return temp * temp;
else
return x * temp * temp;
}
|
Python3
def power(x, y):
temp = 0
if (y = = 0 ):
return 1
temp = power(x, int (y / 2 ))
if (y % 2 = = 0 )
return temp * temp
else
return x * temp * temp
|
C#
static int power( int x, int y)
{
int temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else
return x * temp * temp;
}
|
Javascript
<script>
function power(x , y)
{
var temp;
if ( y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp*temp;
else
return x*temp*temp;
}
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(log n), for recursive call stack
Extend the pow function to work for negative n and float x:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float power( float x, int y)
{
float temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else {
if (y > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
int main()
{
float x = 2;
int y = -3;
cout << power(x, y);
return 0;
}
|
C
#include <stdio.h>
float power( float x, int y)
{
float temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else {
if (y > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
int main()
{
float x = 2;
int y = -3;
printf ( "%f" , power(x, y));
return 0;
}
|
Java
class GFG {
static float power( float x, int y)
{
float temp;
if (y == 0 )
return 1 ;
temp = power(x, y / 2 );
if (y % 2 == 0 )
return temp * temp;
else {
if (y > 0 )
return x * temp * temp;
else
return (temp * temp) / x;
}
}
public static void main(String[] args)
{
float x = 2 ;
int y = - 3 ;
System.out.printf( "%f" , power(x, y));
}
}
|
Python3
def power(x, y):
if (y = = 0 ):
return 1
temp = power(x, int (y / 2 ))
if (y % 2 = = 0 ):
return temp * temp
else :
if (y > 0 ):
return x * temp * temp
else :
return (temp * temp) / x
if __name__ = = "__main__" :
x, y = 2 , - 3
print ( '%.6f' % (power(x, y)))
|
C#
using System;
public class GFG {
static float power( float x, int y)
{
float temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else {
if (y > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
public static void Main()
{
float x = 2;
int y = -3;
Console.Write(power(x, y));
}
}
|
Javascript
<script>
function power(x, y)
{
var temp;
if (y == 0)
return 1;
temp = power(x, parseInt(y / 2));
if (y % 2 == 0)
return temp * temp;
else
{
if (y > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
var x = 2;
var y = -3;
document.write( power(x, y).toFixed(6));
</script>
|
PHP
<?php
function power( $x , $y )
{
$temp ;
if ( $y == 0)
return 1;
$temp = power( $x , $y / 2);
if ( $y % 2 == 0)
return $temp * $temp ;
else
{
if ( $y > 0)
return $x *
$temp * $temp ;
else
return ( $temp *
$temp ) / $x ;
}
}
$x = 2;
$y = -3;
echo power( $x , $y );
?>
|
Time Complexity: O(log |n|)
Auxiliary Space: O(log |n|) , for recursive call stack
Program to calculate pow(x,n) using inbuilt power function:
To solve the problem follow the below idea:
We can use inbuilt power function pow(x, n) to calculate xn
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int power( int x, int n)
{
return ( int ) pow (x, n);
}
int main()
{
int x = 2;
int n = 3;
cout << (power(x, n));
}
|
Java
import java.io.*;
class GFG {
public static int power( int x, int n)
{
return ( int )Math.pow(x, n);
}
public static void main(String[] args)
{
int x = 2 ;
int n = 3 ;
System.out.println(power(x, n));
}
}
|
Python3
def power(x, n):
return pow (x, n)
if __name__ = = "__main__" :
x = 2
n = 3
print (power(x, n))
|
C#
using System;
public class GFG {
public static int power( int x, int n)
{
return ( int )Math.Pow(x, n);
}
static public void Main()
{
int x = 2;
int n = 3;
Console.WriteLine(power(x, n));
}
}
|
Javascript
<script>
function power( x, n)
{
return parseInt(Math.pow(x, n));
}
let x = 2;
let n = 3;
document.write(power(x, n));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1), for recursive call stack
Program to calculate pow(x,n) using Binary operators:
To solve the problem follow the below idea:
Some important concepts related to this approach:
- Every number can be written as the sum of powers of 2
- We can traverse through all the bits of a number from LSB to MSB in O(log n) time.
Illustration:
3^10 = 3^8 * 3^2. (10 in binary can be represented as 1010, where from the left side the first 1 represents 3^2 and the second 1 represents 3^8)
3^19 = 3^16 * 3^2 * 3. (19 in binary can be represented as 10011, where from the left side the first 1 represents 3^1 and second 1 represents 3^2 and the third one represents 3^16)
Below is the implementation of the above approach.
C++
#include <iostream>
using namespace std;
int power( int x, int n)
{
int result = 1;
while (n > 0) {
if (n & 1 == 1)
{
result = result * x;
}
x = x * x;
n = n >> 1;
}
return result;
}
int main()
{
int x = 2;
int n = 3;
cout << (power(x, n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int power( int x, int n)
{
int result = 1 ;
while (n > 0 ) {
if (n % 2 != 0 )
{
result = result * x;
}
x = x * x;
n = n >> 1 ;
}
return result;
}
public static void main(String[] args)
{
int x = 2 ;
int n = 3 ;
System.out.println(power(x, n));
}
}
|
Python3
def power(x, n):
result = 1
while (n > 0 ):
if (n % 2 = = 0 ):
x = x * x
n = n / 2
else :
result = result * x
n = n - 1
return result
if __name__ = = "__main__" :
x = 2
n = 3
print ((power(x, n)))
|
C#
using System;
class GFG {
static int power( int x, int n)
{
int result = 1;
while (n > 0) {
if (n % 2 == 0) {
x = x * x;
n = n / 2;
}
else {
result = result * x;
n = n - 1;
}
}
return result;
}
public static void Main(String[] args)
{
int x = 2;
int y = 3;
Console.Write(power(x, y));
}
}
|
Javascript
<script>
function power(x,y)
{
let result = 1;
while (y > 0) {
if (y % 2 == 0)
{
x = x * x;
y = Math.floor(y / 2);
}
else
{
result = result * x;
y = y - 1;
}
}
return result;
}
let x = 2;
let y = 3;
document.write(power(x, y))
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Program to calculate pow(x,n) using Python ** operator:
To solve the problem follow the below idea:
In Python language, we can easily find power of a number using ** operator.
Below is the implementation of the above approach.
Python3
def power(x, n):
return x * * n
if __name__ = = "__main__" :
x = 2
n = 3
print (power(x, n))
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Program to calculate pow(x,n) using Python numpy module:
We can install NumPy by running the following command:
pip install numpy
To solve the problem follow the below idea:
In Python language, we can easily find power of a number using the NumPy library’s “power” function. This function allows you to calculate the power of a number using a single line of code.
Below is the implementation of the above approach.
Python3
import numpy as np
N = 2
X = 3
result = np.power(N, X)
print (result)
|
Output
8
Program to calculate pow(x,n) using math.log2() and ** operator:
Here, we can use the math.log2() in combination with the operator “**” to calculate the power of a number.
C++
#include <iostream>
#include <cmath>
using namespace std;
int calculatePower( int a, int n) {
return round( pow (2, (log2(a) * n)));
}
int main() {
int a = 2;
int n = 3;
cout << calculatePower(a, n) << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int calculatePower( int a, int n) {
return Math.round(( int ) Math.pow( 2 , (Math.log(a) / Math.log( 2 )) * n));
}
public static void main(String[] args) {
int a = 2 ;
int n = 3 ;
System.out.println(calculatePower(a, n));
}
}
|
Python3
import math
def calculatePower(a, n):
return round ( 2 * * (math.log2(a) * n))
if __name__ = = '__main__' :
a = 2
n = 3
print (calculatePower(a, n))
|
C#
using System;
public class MainClass
{
public static int CalculatePower( int a, int n)
{
return ( int )Math.Round(Math.Pow(2, (Math.Log(a) / Math.Log(2)) * n));
}
public static void Main( string [] args)
{
int a = 2;
int n = 3;
Console.WriteLine(CalculatePower(a, n));
}
}
|
Javascript
function calculatePower(a, n) {
return Math.round(Math.pow(a, n));
}
var a = 2;
var n = 3;
console.log(calculatePower(a, n));
|
Program to calculate pow(x,n) using math.exp() function:
In math library, the math.exp() function in Python is used to calculate the value of the mathematical constant e (2.71828…) raised to a given power. It takes a single argument, which is the exponent to which the constant e should be raised, and returns the result as a float. Now, if we use combination of math.log() and math.exp() function, then we can find power of any number.
Python3
import math
def calculatePower(x, n):
ans = math.exp(math.log(x) * n)
ans = round (ans)
return ans
if __name__ = = '__main__' :
x = 2
n = 3
print (calculatePower(x, n))
|
Complexity Analysis:
Time Complexity: O(1), as both math.exp() and math.log() functions run on O(1) time complexity.
Auxiliary Space: O(1), as no extra space is used.
Related Articles:
Write an iterative O(Log y) function for pow(x, y)
Modular Exponentiation (Power in Modular Arithmetic)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.