-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathM0003.cpp
More file actions
104 lines (93 loc) · 1.91 KB
/
M0003.cpp
File metadata and controls
104 lines (93 loc) · 1.91 KB
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
101
102
103
104
/*
Problem Statement: https://www.hackerrank.com/challenges/extra-long-factorials/problem
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class BigInt{
private:
string s;
public:
BigInt(string s){
this->s = s;
}
void add(string m){
s = add(s, m);
}
void multiply(string m){
s = multiply(s, m);
}
string add(vector<string> results){
string sum;
for(int i=0 ; i<results.size() ; i++)
sum = add(sum, results[i]);
return sum;
}
string add(string n, string m){
int carry, i;
carry = i = 0;
reverse(n.begin(), n.end());
reverse(m.begin(), m.end());
if(n.length() < m.length()){
string temp = n;
n = m;
m = temp;
}
for(i=0 ; i<m.length() ; i++){
int sum = (m[i] - '0') + (n[i] - '0') + carry;
n[i] = (sum%10 + '0');
carry = sum/10;
}
while(carry){
if(i == n.length()){
n.append(to_string(carry));
break;
}
int sum = (n[i] - '0') + carry;
n[i] = (sum%10 + '0');
carry = sum/10;
i++;
}
return string(n.rbegin(), n.rend());
}
string multiply(string n, string m){
vector<string> results(m.length());
reverse(n.begin(), n.end());
reverse(m.begin(), m.end());
for(int i=0 ; i<m.length() ; i++){
int carry = 0;
for(int j=0 ; j<n.length() ; j++){
int prod = (m[i] - '0') * (n[j] - '0') + carry;
results[i].append(to_string(prod%10));
carry = prod/10;
}
if(carry)
results[i].append(to_string(carry));
results[i] = string(i, '0') + results[i];
}
for(int i=0 ; i<results.size() ; i++)
reverse(results[i].begin(), results[i].end());
return add(results);
}
friend ostream& operator<<(ostream& os, const BigInt& b){
os<<b.s;
return os;
}
};
void extraLongFactorials(int n) {
BigInt prod("1");
for(int i=n ; i>0 ; i--){
string m = to_string(i);
prod.multiply(m);
}
cout<<prod;
}
int main()
{
int n;
cin>>n;
extraLongFactorials(n);
return 0;
}