-
Notifications
You must be signed in to change notification settings - Fork 1
/
FactorialOfLargeNumber.cpp
100 lines (74 loc) · 2.11 KB
/
FactorialOfLargeNumber.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
*
* Title: Factorial of Large Number
* Description: Calculate the factorial of a large non-negative number N.
* Author: Ajit Panigrahi
* GitHub: https://github.com/AjitZero
* Twitter: https://twitter.com/AjitZero
*
*/
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
// Maximum length of result in terms of number of digits
const int MAX_DIGIT_LENGTH = 200;
/**
* Displays the factorial of a given number N
*
* @param N [Operand for factorial operation]
*/
void FactorialOfLargeNumber(const int N) {
// Creates a vector of `MAX_DIGIT_LENGTH` elements, initialized to zero by default.
vector<int> product(MAX_DIGIT_LENGTH);
// Initialize default value as 1
product[0] = 1;
// Current size of the number stored in product
int digitLength = 0;
// Iterating from 1 till (N + 1)
for (int i = 1; i < N + 1; ++i) {
// Holds the carry bit
int carry = 0;
// Actual multiplication of numbers, digit by digit
for (int j = 0; j <= digitLength; ++j) {
// Multiply next digit
product[j] *= i;
// Add carry if any
product[j] += carry;
// Update carry bit
carry = product[j] / 10;
// If not a single digit, reduce product[j] to single digit
product[j] %= 10;
}
// If carry exists, add it to the end of vector
while (carry) {
// Update digit length
++digitLength;
// Add carry to the end of vector, digit by digit
product[digitLength] = carry % 10;
// Update carry bit
carry /= 10;
}
}
// Output: Display all digits in reverse
for (int i = digitLength; i >= 0; --i) {
cout << product[i];
}
cout << endl;
}
// Driver function
int main() {
int input;
cin >> input;
assert(("Input should be at least 0.", input >= 0));
FactorialOfLargeNumber(input);
return 0;
}
/*
Sample Input:
--------------------
30
Sample Output:
--------------------
265252859812191058636308480000000
*/