問題
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.
例
例 1
入力:
n = 5
期待される出力:
expected = 120
入力:
long long n = 5;
期待される出力:
long long expected = 120;
入力:
long n = 5;
期待される出力:
long expected = 120;
解説
1 × 2 × 3 × 4 × 5 = 120.
例 2
入力:
n = 0
期待される出力:
expected = 1
入力:
long long n = 0;
期待される出力:
long long expected = 1;
入力:
long n = 0;
期待される出力:
long expected = 1;
解説
0! is defined as 1.
解き方のヒント
まずは自分で考えてから、ヒントを 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