Problème
The factorial of n, written n!, is 1 × 2 × … × n. By definition 0! = 1.
Implement factorial(n).
Input
n: A non-negative integer.
Output
Return n!.
Contraintes
0 ≤ n ≤ 20, so the result fits a signed 64-bit integer.
Exemples
Entrée :
n = 5
Sortie attendue :
expected = 120
Entrée :
long long n = 5;
Sortie attendue :
long long expected = 120;
Entrée :
long n = 5;
Sortie attendue :
long expected = 120;
Explication
1 × 2 × 3 × 4 × 5 = 120.
Entrée :
n = 0
Sortie attendue :
expected = 1
Entrée :
long long n = 0;
Sortie attendue :
long long expected = 1;
Entrée :
long n = 0;
Sortie attendue :
long expected = 1;
Explication
0! is defined as 1.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
Factorial multiplies all integers from 1 up to the given number.
Indice 2
An iterative running product is enough, and 0 has a special defined result.
Indice 3
Because the input is small, overflow is the main detail to watch for in other languages.
Complexité attendue
O(n) time, O(1) extra space