Problema
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!.
Vincoli
0 ≤ n ≤ 20, so the result fits a signed 64-bit integer.
Esempi
Input:
n = 5
Output atteso:
expected = 120
Input:
long long n = 5;
Output atteso:
long long expected = 120;
Input:
long n = 5;
Output atteso:
long expected = 120;
Spiegazione
1 × 2 × 3 × 4 × 5 = 120.
Input:
n = 0
Output atteso:
expected = 1
Input:
long long n = 0;
Output atteso:
long long expected = 1;
Input:
long n = 0;
Output atteso:
long expected = 1;
Spiegazione
0! is defined as 1.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Factorial multiplies all integers from 1 up to the given number.
Suggerimento 2
An iterative running product is enough, and 0 has a special defined result.
Suggerimento 3
Because the input is small, overflow is the main detail to watch for in other languages.
Complessità attesa
O(n) time, O(1) extra space