Recursive Factorial
Completed
Write a recursive static long fact(int n) and print fact(n).
Input
One integer 0–20.
Output
n!
Example
Input
5
Output
120
Editor
Java
Hints
Base case: fact(0) = fact(1) = 1.
Solution explanation
Each call waits for a smaller call to finish, then multiplies.
Show solution
import java.util.Scanner;
public class Main {
static long fact(int n) {
if (n <= 1) {
return 1;
}
return n * fact(n - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(fact(sc.nextInt()));
}
}