In this java program, we will learn about how to calculate the power of a number using loops, using Math.pow() method and using recursion.
To calculate the power of a number(AN) we repetitively multiply base number(A) to inself up to exponent(N) times.
For Example
AN = A*A*A*A..... N times A5 = A*A*A*A*A
To understand this java program, you should have understanding of the following Java programming concepts:
Java Program to calculate power of a number using a loop
public class PowerOfNumberLoop { public static void main(String[] args) { int base = 2, exponent = 6, result = 1; for( int i = 1; i <= exponent ; i++) { result = result * base; } System.out.println("2^6 = " +result); } }Output
2^6 = 64
Using the for loop, we multiplying the result by base up to exponent times.
Java Program to calculate power of a number using recursion
public class PowerOfNumberRecursion { // Function to calculate A^N static int power(int base, int exponent) { if (exponent == 0) return 1; else return base * power(base, exponent-1); } public static void main(String[] args) { System.out.println("2^6 = " + power(2, 6)); } }Output
2^6 = 64
In above java program, we are using following recurrence relation to calculate AN.
AN = A*A*A*A..... N times AN = A * AN-1Let power(A, N) is a function to calculate AN. As per the above recurrence equation, To find power(A, N) we can first calculate power(A, N-1) then multiply it with A. power(A, N) = A * power(A, N-1)
Java Program to calculate power of a number using Math.pow() method
public class PowerOfNumberPowMethod { public static void main(String[] args) { int base = 2, exponent = 6; double result = Math.pow(base, exponent); System.out.println("2^6 = " +result); } }Output
2^6 = 64.0
In this program, we use Java's Math.pow() function to calculate the power of a number.