easyBasic Recursion
Factorial of N numbers
Calculate n factorial, the product of all integers from 1 through n. By definition, 0 factorial is 1.
Work through the cases
3 examplesInput notation
An integer n from 0 through 20.Expected result
n factorial.Case 1
Input
5
Expected output
120
Case 2
Input
0
Expected output
1
Case 3
Input
1
Expected output
1
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Multiply n by the factorial of n-1, stopping at 0 or 1. Time and call-stack space: O(n). JavaScript uses BigInt to preserve exact results through 20!.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Long> values = new ArrayList<>();
while (in.hasNextLong()) values.add(in.nextLong());
long[] a = values.stream().mapToLong(Long::longValue).toArray();
long n = a[0];
class R { long f(long k){return k<=1?1:k*f(k-1);} } System.out.println(new R().f(n));
}
}
Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.