Java Calculate a Bounded Factorial
Factorial multiplies the positive integers up to a non-negative input. Its result grows quickly, so a numeric range policy is part of the exercise.
Understand the idea
Use BigInteger when the result should grow beyond long’s fixed range. Start with one, which also gives zero factorial its standard value. Still bound untrusted input by an application resource policy; arbitrary-precision arithmetic is not an unlimited free resource. A loop expresses this simple accumulation without recursive stack growth.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
int count = 12;
if (count < 0) throw new IllegalArgumentException("non-negative input required");
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= count; i++) factorial = factorial.multiply(BigInteger.valueOf(i));
System.out.println(factorial);
}
}
Expected output
479001600Each multiplication returns a new BigInteger value. The accumulator is reassigned to that result, preserving exact integer arithmetic. An input of zero or one skips the loop and leaves the result at one. The mathematical rule does not itself justify accepting a huge input in a public service.
Check the official Java documentation for detailed contracts and supported options.