-
Notifications
You must be signed in to change notification settings - Fork 7
/
CS_31_FactorialOfALargeNumber.cpp
66 lines (62 loc) · 1.32 KB
/
CS_31_FactorialOfALargeNumber.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
#include <bits/stdc++.h>
using namespace std;
// On GFG, this is the solution:
// vector<int> factorial(int N)
// {
// // code here
// vector<int> ans;
// ans.push_back(1);
// int carry = 0;
// for (int i = 2; i <= N; i++)
// {
// for (int j = 0; j < ans.size(); j++)
// {
// int val = ans[j] * i + carry;
// ans[j] = val % 10;
// carry = val / 10;
// }
// // if carry exits
// while (carry)
// {
// ans.push_back(carry % 10);
// carry /= 10;
// }
// }
// reverse(ans.begin(), ans.end());
// return ans;
// }
// On codestudio, this is the solution:
void multiply(string &s, int x)
{
int carry = 0, prod = 1;
for (int i = 0; i < s.length(); i++)
{
prod = (x * (s[i] - '0')) + carry;
carry = prod / 10;
prod = prod % 10;
s[i] = char(prod + '0');
}
while (carry)
{
s.push_back(char((carry % 10) + '0'));
carry /= 10;
}
}
string calculateFactorial(int n)
{
string ans = "1";
for (int i = 2; i <= n; i++)
{
multiply(ans, i);
}
reverse(ans.begin(), ans.end());
return ans;
}
int main()
{
int n;
cin >> n;
string ans = calculateFactorial(n);
cout << ans << endl;
return 0;
}