Read the question, write Java on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Write long factorial(int n). 0! is 1. Read n and print factorial(n).
Examples
Input
5
Output
120
Input
0
Output
1
Hint
- Loop from 2 to n.
Show correct code
Peek only after you have tried. You can still Check your own version.
import java.util.Scanner;
public class Main {
static long factorial(int n) {
long result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(factorial(n));
}
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.