Calculate Power Without Math.pow() in Java
Problem
Raising a number to a whole-number exponent is just multiplying the base by itself that many times, which a loop can do directly without any built-in power function.
Given a base and a non-negative integer exponent, calculate the base raised to that exponent.
Java Program
public class PowerWithoutMathPow {
public static void main(String[] args) {
int base = 2, exponent = 10;
long result = 1; // base^0 is 1, so this is correct even before the loop runs
for (int i = 0; i < exponent; i++) {
result *= base;
}
System.out.println(base + "^" + exponent + " = " + result);
}
}Output
Core Logic
Multiplying a running result by the base once per unit of exponent builds up the power one factor at a time.
- 1
resultstarts at1, the correct answer for any base raised to the power of0. - 2The loop runs exactly
exponenttimes, multiplyingresultbybaseon each pass. - 3By the time the loop ends,
resultholdsbasemultiplied by itselfexponenttimes.
base = 2 and exponent = 10, the loop multiplies by 2 ten times, building result up to 1024.Key Point: Starting result at 1 — not 0 or base — is what makes an exponent of 0 correctly fall out to 1 without any special case.
Why: The loop multiplies the running result by the base once per unit of exponent, and keeps only that single running value.
Key Concepts
Approach 2: Java 8
import java.util.stream.IntStream;
public class PowerWithoutMathPowStream {
public static void main(String[] args) {
int base = 2, exponent = 10;
// Reduces exponent elements down to a single running product, multiplying by base each time
long result = IntStream.rangeClosed(1, exponent).reduce(1, (a, b) -> a * base);
System.out.println(base + "^" + exponent + " = " + result);
}
}
Output
Core Logic
The same repeated multiplication is exactly what Stream's reduce() is built for — folding the base into a running product one step at a time.
- 1
IntStream.rangeClosed(1, exponent)generates exactlyexponentvalues, one per multiplication needed. - 2
.reduce(1, (a, b) -> a * base)starts the running product at1and multiplies it bybaseonce per element in the stream. - 3The second argument
bis never actually used — the stream's only job here is to trigger the right number of multiplications.
base = 2 and exponent = 10, the stream reduces ten times, each multiplying by 2, landing on the same 1024.Key Point: Using a long for the running product keeps this safe from overflow even for larger bases and exponents than this example needs.
Why: reduce() still performs one multiplication per unit of exponent, carrying forward a single running long value.