Условие
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!.
Ограничения
0 ≤ n ≤ 20, so the result fits a signed 64-bit integer.
Примеры
Ввод:
n = 5
Ожидаемый вывод:
expected = 120
Ввод:
long long n = 5;
Ожидаемый вывод:
long long expected = 120;
Ввод:
long n = 5;
Ожидаемый вывод:
long expected = 120;
Пояснение
1 × 2 × 3 × 4 × 5 = 120.
Ввод:
n = 0
Ожидаемый вывод:
expected = 1
Ввод:
long long n = 0;
Ожидаемый вывод:
long long expected = 1;
Ввод:
long n = 0;
Ожидаемый вывод:
long expected = 1;
Пояснение
0! is defined as 1.
Как подступиться
Сначала попробуйте сами, затем открывайте подсказки по одной.
Подсказка 1
Factorial multiplies all integers from 1 up to the given number.
Подсказка 2
An iterative running product is enough, and 0 has a special defined result.
Подсказка 3
Because the input is small, overflow is the main detail to watch for in other languages.
Ожидаемая сложность
O(n) time, O(1) extra space