Read the question, write JavaScript on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Write a function factorial(n) that returns n! (the product 1 × 2 × … × n). By definition 0! is 1.
The main part already reads n and logs factorial(n) — you only fill in the function.
Input. One line: an integer n ≥ 0.
Output. One integer: n!
Constraints
- 0 ≤ n ≤ 18 (stays an exact integer).
Examples
Input
5
Output
120
Input
0
Output
1
Hint
- Start result at 1 and multiply by every number from 2 to n.
- When n is 0 or 1 the loop body never runs, so result stays 1 — exactly right.
Show correct code
Peek only after you have tried. You can still Check your own version.
function factorial(n) {
let result = 1;
for (let i = 2; i <= n; i++) result *= i;
return result;
}
const n = Number(readLine());
console.log(factorial(n));
main.jsconsole.log · readLine() · Ctrl + Enter
ResultIdle
Run to see output. Check grades the tests.