Practice › Basics
Factorial
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Print n! = 1 × 2 × … × n. By definition 0! = 1.
Input
One integer n.
Output
The value of n!.
Constraints
- 0 ≤ n ≤ 20
20! = 2432902008176640000 needs a 64-bit integer.
Example 1
Input
5
Output
120
Example 2
Input
0
Output
1
Hints
- Multiply 1 × 2 × … × n in a loop, starting from 1 so that 0! = 1.
- 20! ≈ 2.4 × 10^18 — it needs a 64-bit integer.
Approach
Start with result = 1 and multiply by every i from 2 to n. Starting at 1 handles 0! = 1 automatically. 20! is the largest factorial that fits in a signed 64-bit integer, which is exactly the limit here.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
long long result = 1;
for (int i = 2; i <= n; i++) result *= i;
cout << result << "\n";
return 0;
}Python solution
n = int(input())
result = 1
for i in range(2, n + 1):
result *= i
print(result)Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long result = 1;
for (int i = 2; i <= n; i++) result *= i;
System.out.println(result);
}
}