Java Program to Calculate Power of a Number
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 program to find the power of a number// using RecursionclassGFG {// Function to calculate N raised to the power Pstaticintpower(intN,intP){if(P ==0)return1;elsereturnN * power(N, P -1);}// Driver codepublicstaticvoidmain(String[] args){intN =2;intP =3;System.out.println(power(N, P));}}chevron_rightfilter_noneOutput:8
- Method 2: With the help of Loop
// Java program to find the power of a number// with the help of loopclassGFG {// Function to calculate N raised to the power Pstaticintpower(intN,intP){intpow =1;for(inti =1; i <= P; i++)pow *= N;returnpow;}// Driver codepublicstaticvoidmain(String[] args){intN =2;intP =3;System.out.println(power(N, P));}}chevron_rightfilter_noneOutput:8
- Method 3: Using Math.pow() method
// Java program to find the power of a number// using Math.pow() methodimportjava.lang.Math;classGFG {// Function to calculate N raised to the power Pstaticdoublepower(intN,intP){returnMath.pow(N, P);}// Driver codepublicstaticvoidmain(String[] args){intN =2;intP =3;System.out.println(power(N, P));}}chevron_rightfilter_noneOutput:8.0
Recommended Posts:
- Program to calculate the number of odd days in given number of years
- Program for power of a complex number in O(log n)
- Check if given number is a power of d where d is a power of 2
- C program to calculate the value of nPr
- Program to calculate value of nCr
- Program to Calculate e^x by Recursion
- Program to calculate the value of nCr Efficiently
- Write a program to calculate pow(x,n)
- Efficient program to calculate e^x
- Program to calculate the value of sin(x) and cos(x) using Expansion
- Program to calculate Area Of Octagon
- Program to calculate the area of Kite
- Program to calculate Profit Or Loss
- Program to calculate Root Mean Square
- Program to calculate distance between two points
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

