Power without Math.pow() in Java
Compute a^b using a loop instead of Math.pow().
BeginnerModule 1: Basic Java ProgramsExample 16 of 20
power-without-math-pow.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);67 System.out.print("Enter base (a): ");8 int a = sc.nextInt();9 System.out.print("Enter exponent (b): ");10 int b = sc.nextInt();1112 long result = 1;13 for (int i = 1; i <= b; i++) {14 result *= a;15 }1617 System.out.println(a + " raised to " + b + " = " + result);1819 sc.close();20 }21}
Output
Enter base (a): 2 Enter exponent (b): 5 2 raised to 5 = 32
What's going on
We multiply the base by itself b times in a loop to compute a^b.