Factorial with a Loop
Problem
Read n (0 to 20). Print n! = 1 * 2 * ... * n. By definition 0! is 1.
Constraints
- 0 <= n <= 20
Examples
Input
5
Output
120
Solutions
The result grows very fast: 20! is about 2.4 * 10^18, which is near the limit of a Java long. For n above 20 you need BigInteger (see the big factorial problem).
/*
* Problem : Factorial.
* Input : One integer n.
* Output : n!.
* Approach: A multiplication loop.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(long n) {
// Step 1: Start with 1. This is also the answer for n = 0.
long result = 1;
// Step 2: Multiply by each number from 2 to n. 20! fits in a long (about 2.4 * 10^18).
for (long i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
System.out.println(solve(n));
}
}
Hints (1)
- What is the biggest n whose factorial fits in a long?