Write program to calculate pow(x, n)
Last Updated :
02 Aug, 2024
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++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Naive iterative solution to calculate pow(x, n)
long power(int x, unsigned n)
{
// Initialize result to 1
long long pow = 1;
// Multiply x for n times
for (int i = 0; i < n; i++) {
pow = pow * x;
}
return pow;
}
// Driver code
int main(void)
{
int x = 2;
unsigned n = 3;
// Function call
int result = power(x, n);
cout << result << endl;
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class Gfg {
// Naive iterative solution to calculate pow(x, n)
public static long power(int x, int n)
{
// Initialize result by 1
long pow = 1L;
// Multiply x for n times
for (int i = 0; i < n; i++) {
pow = pow * x;
}
return pow;
}
// Driver code
public static void main(String[] args)
{
int x = 2;
int n = 3;
System.out.println(power(x, n));
}
};
Python
# Python3 program for the above approach
def power(x, n):
# initialize result by 1
pow = 1
# Multiply x for n times
for i in range(n):
pow = pow * x
return pow
# Driver code
if __name__ == '__main__':
x = 2
n = 3
# Function call
print(power(x, n))
C#
// C# program for the above approach
using System;
public class Gfg {
// Naive iterative solution to calculate pow(x, n)
static long power(int x, int n)
{
// Initialize result by 1
long pow = 1L;
// Multiply x for n times
for (int i = 0; i < n; i++) {
pow = pow * x;
}
return pow;
}
// Driver code
public static void Main(String[] args)
{
int x = 2;
int n = 3;
Console.WriteLine(power(x, n));
}
};
// This code contributed by Pushpesh Raj
JavaScript
// Naive iterative solution to calculate pow(x, n)
function power( x, n)
{
// Initialize result to 1
let pow = 1;
// Multiply x for n times
for (let i = 0; i < n; i++) {
pow = pow * x;
}
return pow;
}
// Driver code
let x = 2;
let n = 3;
// Function call
let result = power(x, n);
console.log( result );
// This code is contributed by garg28harsh.
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++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
int power(int x, int n)
{
// If x^0 return 1
if (n == 0)
return 1;
// If we need to find of 0^y
if (x == 0)
return 0;
// For all other cases
return x * power(x, n - 1);
}
// Driver Code
int main()
{
int x = 2;
int n = 3;
// Function call
cout << (power(x, n));
}
// This code is contributed by Aditya Kumar (adityakumar129)
C
// C program for the above approach
#include <stdio.h>
int power(int x, int n)
{
// If x^0 return 1
if (n == 0)
return 1;
// If we need to find of 0^y
if (x == 0)
return 0;
// For all other cases
return x * power(x, n - 1);
}
// Driver Code
int main()
{
int x = 2;
int n = 3;
// Function call
printf("%d\n", power(x, n));
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java program for the above approach
import java.io.*;
class GFG {
public static int power(int x, int n)
{
// If x^0 return 1
if (n == 0)
return 1;
// If we need to find of 0^y
if (x == 0)
return 0;
// For all other cases
return x * power(x, n - 1);
}
// Driver Code
public static void main(String[] args)
{
int x = 2;
int n = 3;
// Function call
System.out.println(power(x, n));
}
}
Python
# Python3 program for the above approach
def power(x, n):
# If x^0 return 1
if (n == 0):
return 1
# If we need to find of 0^y
if (x == 0):
return 0
# For all other cases
return x * power(x, n - 1)
# Driver Code
if __name__ == "__main__":
x = 2
n = 3
# Function call
print(power(x, n))
# This code is contributed by shivani.
C#
// C# program for the above approach
using System;
class GFG {
public static int power(int x, int n)
{
// If x^0 return 1
if (n == 0)
return 1;
// If we need to find of 0^y
if (x == 0)
return 0;
// For all other cases
return x * power(x, n - 1);
}
// Driver Code
public static void Main(String[] args)
{
int x = 2;
int n = 3;
// Function call
Console.WriteLine(power(x, n));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// javascript program for the above approach
function power(x , n) {
// If x^0 return 1
if (n == 0)
return 1;
if (x == 0)
return 0;
// For all other cases
return x * power(x, n - 1);
}
// Driver Code
var x = 2;
var n = 3;
document.write(power(x, n));
// This code is contributed by Rajput-Ji
</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++
// C++ program to calculate pow(x,n)
#include <bits/stdc++.h>
using namespace std;
class gfg {
/* Function to calculate x raised to the power y */
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);
}
};
/* Driver code */
int main()
{
gfg g;
int x = 2;
unsigned int y = 3;
// Function call
cout << g.power(x, y);
return 0;
}
// This code is contributed by SoM15242
C
// C program to calculate pow(x,n)
#include <stdio.h>
/* Function to calculate x raised to the power y */
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);
}
/* Driver code */
int main()
{
int x = 2;
unsigned int y = 3;
// Function call
printf("%d", power(x, y));
return 0;
}
Java
// Java program to calculate pow(x,n)
class GFG {
/* Function to calculate x raised to the power y */
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);
}
// Driver code
public static void main(String[] args)
{
int x = 2;
int y = 3;
// Function call
System.out.printf("%d", power(x, y));
}
}
// This code is contributed by Smitha Dinesh Semwal
Python
# Python3 program to calculate pow(x,n)
# Function to calculate x
# raised to the power y
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)))
# Driver Code
if __name__ == "__main__":
x = 2
y = 3
# Function call
print(power(x, y))
# This code is contributed by Smitha Dinesh Semwal.
C#
// C# program to calculate pow(x,n)
using System;
public class GFG {
// Function to calculate x raised to the power y
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);
}
// Driver code
public static void Main()
{
int x = 2;
int y = 3;
// Function call
Console.Write(power(x, y));
}
}
// This code is contributed by shiv_bhakt.
JavaScript
<script>
// Javascript program to calculate pow(x,n)
// Function to calculate x
// raised to the power y
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));
}
// Driver code
let x = 2;
let y = 3;
document.write(power(x, y));
// This code is contributed by mukesh07
</script>
PHP
<?php
// php program to calculate pow(x,n)
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);
}
// Driver Code
$x = 2;
$y = 3;
// Function call
echo power($x, $y);
// This code is contributed by ajit
?>
Time Complexity: O(2^y) , due to redundant calculations from multiple recursive calls.
Auxiliary Space: O(log y)
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++
/* Function to calculate x raised to the power y in
* O(logn)*/
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;
}
// This code is contributed by Shubhamsingh10
C
/* Function to calculate x raised to the power y in
* O(logn)*/
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
/* Function to calculate x raised to the power y in
* O(logn)*/
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;
}
// This code is contributed by divyeshrabadiya07.
Python
# Function to calculate x raised to the power y in O(logn)
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
# This code is contributed by avanitrachhadiya2155
C#
/* Function to calculate x raised to the power y in
* O(logn)*/
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;
}
// This code is contributed by divyesh072019.
JavaScript
<script>
/* Function to calculate x raised to the power y in O(logn)*/
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;
}
// This code is contributed by todaysgaurav
</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++
/* Extended version of power function
that can work for float x and negative y*/
#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;
}
}
// Driver Code
int main()
{
float x = 2;
int y = -3;
// Function call
cout << power(x, y);
return 0;
}
// This is code is contributed
// by rathbhupendra
C
/* Extended version of power function that can work
for float x and negative y*/
#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;
}
}
/* Driver code */
int main()
{
float x = 2;
int y = -3;
// Function call
printf("%f", power(x, y));
return 0;
}
Java
/* Java code for extended version of power function
that can work for float x and negative y */
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;
}
}
/* Driver code */
public static void main(String[] args)
{
float x = 2;
int y = -3;
// Function call
System.out.printf("%f", power(x, y));
}
}
// This code is contributed by Smitha Dinesh Semwal.
Python
# Python3 code for extended version
# of power function that can work
# for float x and negative y
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
# Driver Code
if __name__ == "__main__":
x, y = 2, -3
# Function call
print('%.6f' % (power(x, y)))
# This code is contributed by Smitha Dinesh Semwal.
C#
// C# code for extended version of power function
// that can work for float x and negative y
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;
}
}
// Driver code
public static void Main()
{
float x = 2;
int y = -3;
// Function call
Console.Write(power(x, y));
}
}
// This code is contributed by shiv_bhakt.
JavaScript
<script>
// Javascript code for extended
// version of power function that
// can work for var x and negative y
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;
}
}
// Driver code
var x = 2;
var y = -3;
document.write( power(x, y).toFixed(6));
// This code is contributed by aashish1995
</script>
PHP
<?php
// Extended version of power
// function that can work
// for float x and negative y
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;
}
}
// Driver Code
$x = 2;
$y = -3;
// Function call
echo power($x, $y);
// This code is contributed by ajit
?>
Rust
/*
Below funtion implements pow functionality in rust by gaurav nv
*/
fn powg(x:i32,y:i32) -> f32{
if y == 0 {
return 1 as f32;
} else if y == 1{
return x as f32;
}
let temp:f32 = powg(x, y/2);
if y>0 {
if y%2 == 0 {
return temp * temp;
} else {
return temp * temp * (x as f32);
}
} else {
if y%2 == 0 {
return temp * temp;
} else {
return temp * temp / (x as f32);
}
}
}
fn main() {
println!("{}",powg(2, -3));
}
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++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
int power(int x, int n)
{
// return type of pow()
// function is double
return (int)pow(x, n);
}
// Driver Code
int main()
{
int x = 2;
int n = 3;
// Function call
cout << (power(x, n));
}
// This code is contributed by hemantraj712.
Java
// Java program for the above approach
import java.io.*;
class GFG {
public static int power(int x, int n)
{
// Math.pow() is a function that
// return floating number
return (int)Math.pow(x, n);
}
// Driver Code
public static void main(String[] args)
{
int x = 2;
int n = 3;
// Function call
System.out.println(power(x, n));
}
}
Python
# Python3 program for the above approach
def power(x, n):
# Return type of pow()
# function is double
return pow(x, n)
# Driver Code
if __name__ == "__main__":
x = 2
n = 3
# Function call
print(power(x, n))
# This code is contributed by susmitakundugoaldanga
C#
// C# program for the above approach
using System;
public class GFG {
public static int power(int x, int n)
{
// Math.pow() is a function that
// return floating number
return (int)Math.Pow(x, n);
}
// Driver code
static public void Main()
{
int x = 2;
int n = 3;
// Function call
Console.WriteLine(power(x, n));
}
}
JavaScript
<script>
// Javascript program for the above approach
function power( x, n)
{
// Math.pow() is a function that
// return floating number
return parseInt(Math.pow(x, n));
}
// Driver Code
let x = 2;
let n = 3;
document.write(power(x, n));
// This code is contributed by sravan kumar
</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++
// C++ program for the above approach
#include <iostream>
using namespace std;
int power(int x, int n)
{
int result = 1;
while (n > 0) {
if (n & 1 == 1) // y is odd
{
result = result * x;
}
x = x * x;
n = n >> 1; // y=y/2;
}
return result;
}
// Driver Code
int main()
{
int x = 2;
int n = 3;
// Function call
cout << (power(x, n));
return 0;
}
// This code is contributed bySuruchi Kumari
Java
// Java program for above approach
import java.io.*;
class GFG {
static int power(int x, int n)
{
int result = 1;
while (n > 0) {
if (n % 2 != 0) // y is odd
{
result = result * x;
}
x = x * x;
n = n >> 1; // y=y/2;
}
return result;
}
// Driver Code
public static void main(String[] args)
{
int x = 2;
int n = 3;
// Function call
System.out.println(power(x, n));
}
}
// This code is contributed by Suruchi Kumari
Python
# Python3 program for the above approach
def power(x, n):
result = 1
while (n > 0):
if (n % 2 == 0):
# y is even
x = x * x
n = n / 2
else:
# y isn't even
result = result * x
n = n - 1
return result
# Driver Code
if __name__ == "__main__":
x = 2
n = 3
# Function call
print((power(x, n)))
# This code is contributed by shivanisinghss2110
C#
// C# program for above approach
using System;
class GFG {
static int power(int x, int n)
{
int result = 1;
while (n > 0) {
// y is even
if (n % 2 == 0) {
x = x * x;
n = n / 2;
}
// y isn't even
else {
result = result * x;
n = n - 1;
}
}
return result;
}
// Driver Code
public static void Main(String[] args)
{
int x = 2;
int y = 3;
// Function call
Console.Write(power(x, y));
}
}
// This code is contributed by shivanisinghss2110
JavaScript
<script>
// Javascript program for the above approach
function power(x,y)
{
let result = 1;
while (y > 0) {
if (y % 2 == 0) // y is even
{
x = x * x;
y = Math.floor(y / 2);
}
else // y isn't even
{
result = result * x;
y = y - 1;
}
}
return result;
}
// Driver Code
let x = 2;
let y = 3;
document.write(power(x, y))
// This code is contributed by rag2127
</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.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to calculate power
double calculatePower(double x, int n) {
// Calculate the power using the pow function from cmath library
return pow(x, n);
}
// Main function
int main() {
// Input values
double x = 2;
int n = 3;
// Function call
double result = calculatePower(x, n);
// Output the result
cout << result << endl;
return 0;
}
Java
public class Main {
// Function to calculate power
public static double calculatePower(double x, int n) {
// Calculate the power using the exponentiation operator (**)
return Math.pow(x, n);
}
// Main function
public static void main(String[] args) {
// Input values
double x = 2;
int n = 3;
// Function call
double result = calculatePower(x, n);
// Output the result
System.out.println(result);
}
}
Python
# Python program to illustrate use of ** operator
# to calculate power of a number
def power(x, n):
# Calculate the power
return x**n
# Driver Code
if __name__ == "__main__":
x = 2
n = 3
# Function call
print(power(x, n))
# This code is contributed by Susobhan Akhuli
C#
using System;
class Program
{
// Function to calculate power
static double CalculatePower(double x, int n)
{
// Calculate the power using the Math.Pow method
return Math.Pow(x, n);
}
// Main function
static void Main(string[] args)
{
// Input values
double x = 2;
int n = 3;
// Function call
double result = CalculatePower(x, n);
// Output the result
Console.WriteLine(result);
}
}
// This code is contributed by Utkarsh
JavaScript
function GFG(x, n) {
// Calculate the power
return x ** n;
}
// Main function
function main() {
// Input values
const x = 2;
const n = 3;
// Function call
const result = GFG(x, n);
// Output the result
console.log(result);
}
// Execute the main function
main();
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.
C++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int N = 2;
int X = 3;
int result = pow(N, X);
cout << result << endl;
return 0;
}
Java
import java.lang.Math;
public class Main {
public static void main(String[] args) {
int N = 2;
int X = 3;
int result = (int) Math.pow(N, X);
System.out.println(result); // Output: 8
}
}
//this code is contributed by Adarsh.
Python
import numpy as np
N = 2
X = 3
result = np.power(N, X)
print(result) # Output: 8
#This code is contributed by Susobhan Akhuli
JavaScript
// In this example, we're calculating N raised to the power of X
// where N = 2 and X = 3
// Calculating the result
const N = 2;
const X = 3;
// In JavaScript, the Math.pow() function is used to calculate the power of a number
// The Math.pow() function returns the base to the exponent power, that is, base^exponent
const result = Math.pow(N, X);
// Printing the result
console.log(result);
//This code is contributed by Utkarsh
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 {
// Function to calculate a^n using log2 and pow methods
public static int calculatePower(int a, int n) {
// Calculate a^n using the log2 and pow methods
// The result is rounded to the nearest integer
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));
}
}
Python
import math
def calculatePower(a, n):
return round(2 ** (math.log2(a) * n))
# Driver code
if __name__ == '__main__':
a = 2
n = 3
print(calculatePower(a, n)) # Output: a^n
# This code is contributed by Susobhan Akhuli
C#
using System;
public class MainClass
{
// Function to calculate a^n using log2 and pow methods
public static int CalculatePower(int a, int n)
{
// Calculate a^n using the log2 and pow methods
// The result is rounded to the nearest integer
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 to calculate a^n using Math.pow
function calculatePower(a, n) {
// Calculate a^n using Math.pow
return Math.round(Math.pow(a, n));
}
// Test the function
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.
C++
#include <cmath>
#include <iostream>
using namespace std;
// Function to calculate the power of a number
int calculatePower(int x, int n)
{
// Calculate the power using the exp and log functions
// from the cmath library
double result = exp(log(x) * n);
// Round the result to the nearest integer
result = round(result);
return static_cast<int>(result);
}
int main()
{
int x = 2;
int n = 3;
// Function call
cout << "Result: " << calculatePower(x, n) << endl;
return 0;
}
Java
import java.lang.Math;
public class Main {
// Function to calculate the power of a number
static int calculatePower(int x, int n) {
// Calculate the power using the exp and log functions
// from the Math library
double result = Math.exp(Math.log(x) * n);
// Round the result to the nearest integer
result = Math.round(result);
return (int) result;
}
public static void main(String[] args) {
int x = 2;
int n = 3;
// Function call
System.out.println("Result: " + calculatePower(x, n));
}
}
Python
import math
def calculatePower(x, n):
ans = math.exp(math.log(x) * n)
ans = round(ans)
return ans
# Driver code
if __name__ == '__main__':
x = 2
n = 3
print(calculatePower(x, n)) # Output: x^n
# This code is contributed by Susobhan Akhuli
C#
using System;
class Program {
// Function to calculate the power of a number
static int CalculatePower(int x, int n)
{
// Calculate the power using the Math.Pow function
double result = Math.Pow(x, n);
// Round the result to the nearest integer
result = Math.Round(result);
return (int)result;
}
static void Main()
{
int x = 2;
int n = 3;
// Function call
Console.WriteLine("Result: "
+ CalculatePower(x, n));
}
}
JavaScript
function GFG(x, n) {
// Using the mathematical property to
// calculate the power
const ans = Math.round(Math.exp(Math.log(x) * n));
return ans;
}
// Driver Code
const x = 2;
const n = 3;
console.log(GFG(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.
Similar Reads
Divide and Conquer Algorithm
Divide and Conquer algorithm is a problem-solving strategy that involves. Divide : Break the given problem into smaller non-overlapping problems.Conquer : Solve Smaller ProblemsCombine : Use the Solutions of Smaller Problems to find the overall result.Examples of Divide and Conquer are Merge Sort, Q
1 min read
Introduction to Divide and Conquer Algorithm
Divide and Conquer Algorithm is a problem-solving technique used to solve problems by dividing the main problem into subproblems, solving them individually and then merging them to find solution to the original problem. In this article, we are going to discuss how Divide and Conquer Algorithm is hel
12 min read
Dynamic Programming vs Divide-and-Conquer
In this article I’m trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the mai
12 min read
Decrease and Conquer
As divide-and-conquer approach is already discussed, which include following steps: Divide the problem into a number of subproblems that are smaller instances of the same problem. Conquer the sub problems by solving them recursively. If the subproblem sizes are small enough, however, just solve the
5 min read
Advanced master theorem for divide and conquer recurrences
The Master Theorem is a tool used to solve recurrence relations that arise in the analysis of divide-and-conquer algorithms. The Master Theorem provides a systematic way of solving recurrence relations of the form: T(n) = aT(n/b) + f(n) where a, b, and f(n) are positive functions and n is the size o
5 min read
Some standard Divide and Conquer Algorithms
Write program to calculate pow(x, n)
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 = 3Output : 8 Input : x = 7, n = 2Output : 49 Naive Approach: To solve the problem follow the below idea: A simple solution to calculate pow(x, n
15+ min read
Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
Given two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120. For simplicity, let the length of two strings be same and be n. A Naive Approach is to follow the proc
15+ min read
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Given two square matrices A and B of size n x n each, find their multiplication matrix. Naive Method: Following is a simple way to multiply two matrices. C/C++ Code void multiply(int A[][N], int B[][N], int C[][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { C[i][j] = 0; for
15+ min read
Convex Hull using Divide and Conquer Algorithm
In computational geometry, a convex hull is the smallest convex polygon that contains a given set of points. It is a fundamental concept with applications in various fields such as computer graphics, robotics, and image processing. Importance of Convex Hull:Convex hulls are important in computationa
15 min read
Quickhull Algorithm for Convex Hull
Given a set of points, a Convex hull is the smallest convex polygon containing all the given points. Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};Output : The points in convex hull are: (0, 0) (0, 3) (3, 1) (4, 4)Input : points[] = {{0, 3}, {1, 1}Output : Not P
14 min read
Binary Search based problems
Find Peak Element in Array
Given an array arr[] where no two adjacent elements are same, find the index of a peak element. An element is considered to be a peak element if it is strictly greater than its adjacent elements. If there are multiple peak elements, return the index of any one of them. Note: Consider the element bef
13 min read
Check for Majority Element in a sorted array
Given an array arr of N elements, A majority element in an array arr of size N is an element that appears more than N/2 times in the array. The task is to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true i
15+ min read
K-th Element of Merged Two Sorted Arrays
Given two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays. Examples: Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5Output: 6Explanation: The final sorted array is [1
15+ min read
Find the number of zeroes
Given an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array.Examples : Input: arr[] = {1, 1, 1, 1, 0, 0} Output: 2 Input: arr[] = {1, 0, 0, 0, 0} Output: 4 Input: arr[] = {0, 0, 0} Output: 3 Input: arr[] = {1, 1, 1, 1} O
12 min read
Rotation Count in a Rotated Sorted array
Given an array arr[] having distinct numbers sorted in increasing order and the array has been right rotated (i.e, the last element will be cyclically shifted to the starting position of the array) k number of times, the task is to find the value of k. Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}O
13 min read
Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes p
11 min read
Median of two Sorted Arrays of Different Sizes
Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array. This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal s
15+ min read
The Painter's Partition Problem using Binary Search
Given are N boards of with length of each given in the form of array, and K painters, such that each painter takes 1 unit of time to paint 1 unit of the board. The task is to find the minimum time to paint all boards under the constraints that any painter will only paint continuous sections of board
11 min read
Some practice problems on Divide and Conquer algorithm
Square root of an integer
Given a positive integer n, find its square root. If n is not a perfect square, then return floor of √n. Examples : Input: n = 4Output: 2Explanation: The square root of 4 is 2. Input: n = 11Output: 3Explanation: The square root of 11 lies in between 3 and 4 so floor of the square root is 3. Table of
13 min read
Maximum and minimum of an array using minimum number of comparisons
Given an array of size N. The task is to find the maximum and the minimum element of the array using the minimum number of comparisons. Examples: Input: arr[] = {3, 5, 4, 1, 9}Output: Minimum element is: 1 Maximum element is: 9 Input: arr[] = {22, 14, 8, 17, 35, 3}Output: Minimum element is: 3 Maxim
15+ min read
Find frequency of each element in a limited range array in less than O(n) time
Given a sorted array arr[] of positive integers, the task is to find the frequency for each element in the array. Assume all elements in the array are less than some constant M Note: Do this without traversing the complete array. i.e. expected time complexity is less than O(n) Examples: Input: arr[]
15+ min read
Tiling Problem using Divide and Conquer algorithm
Given a n by n board where n is of form 2k where k >= 1 (Basically n is a power of 2 with minimum value as 2). The board has one missing cell (of size 1 x 1). Fill the board using L shaped tiles. A L shaped tile is a 2 x 2 square with one cell of size 1x1 missing. Figure 1: An example inputThis p
15+ min read
Count Inversions of an Array
Given an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j. Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorte
15+ min read
The Skyline Problem | Set-1
Given n rectangular buildings in a 2-dimensional city, computes the skyline of these buildings, eliminating hidden lines. The main task is to view buildings from a side and remove all sections that are not visible. All buildings share a common bottom and every building is represented by a triplet (l
14 min read
Search in a Row-wise and Column-wise Sorted 2D Array using Divide and Conquer algorithm
Given an n x n matrix, where every row and column is sorted in increasing order. Given a key, how to decide whether this key is in the matrix. A linear time complexity is discussed in the previous post. This problem can also be a very good example for divide and conquer algorithms. Following is divi
15+ min read
Allocate Minimum Pages
Given an array arr[] and an integer k, where arr[i] denotes the number of pages of a book and k denotes total number of students. All the books need to be allocated to k students in contiguous manner, with each student getting at least one book. The task is to minimize the maximum number of pages al
15+ min read