Power without Math.pow()

Compute a^b using a loop instead of Math.pow().

JavaBeginner
Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter base (a): ");
        int a = sc.nextInt();
        System.out.print("Enter exponent (b): ");
        int b = sc.nextInt();

        long result = 1;
        for (int i = 1; i <= b; i++) {
            result *= a;
        }

        System.out.println(a + " raised to " + b + " = " + result);

        sc.close();
    }
}

Output

Enter base (a): 2
Enter exponent (b): 5
2 raised to 5 = 32

We multiply the base by itself b times in a loop to compute a^b.