Java Program to Calculate Power of a Number
Last Updated :
04 Jun, 2022
Given a number N and a power P, the task is to find the exponent of this number raised to the given power, i.e. NP. Examples:
Input: N = 5, P = 2
Output: 25
Input: N = 2, P = 5
Output: 32
Below are the various ways to find NP:
- Method 1: Using Recursion
Java
class GFG {
static int power( int N, int P)
{
if (P == 0 )
return 1 ;
else
return N * power(N, P - 1 );
}
public static void main(String[] args)
{
int N = 2 ;
int P = 3 ;
System.out.println(power(N, P));
}
}
|
- Method 2: With the help of Loop
Java
class GFG {
static int power( int N, int P)
{
int pow = 1 ;
for ( int i = 1 ; i <= P; i++)
pow *= N;
return pow;
}
public static void main(String[] args)
{
int N = 2 ;
int P = 3 ;
System.out.println(power(N, P));
}
}
|
Java
import java.lang.Math;
class GFG {
static double power( int N, int P)
{
return Math.pow(N, P);
}
public static void main(String[] args)
{
int N = 2 ;
int P = 3 ;
System.out.println(power(N, P));
}
}
|
- Method 4 : Efficient Approach
In this approach I am going to calculate power of given base using bit manipulation with logarithmic time complexity
Java
public class GFG {
public static void main(String[] args) {
int base = 2 ;
int power = 3 ;
int ans = 1 ;
while (power > 0 ){
if ((power& 1 )== 1 ){
ans = ans * base;
}
base = base * base;
power = power >> 1 ;
}
System.out.println(ans);
}
}
|
Time complexity : O(logb)
Share your thoughts in the comments
Please Login to comment...