[InterviewBit] Large Factorial

Large Factorial

  • Time :
  • Space :
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
string mul(string A, string B) {
string res = string(A.length() + B.length() + 1, '0');
reverse(begin(A), end(A));
reverse(begin(B), end(B));
for(int i = 0; i < A.length(); i++) {
int carry = 0;
for(int j = 0; j < B.length(); j++) {
int now = res[i + j] - '0' + (A[i] - '0') * (B[j] - '0') + carry;
carry = now / 10;
res[i + j] = (now % 10) + '0';
}
int p = i + B.length();
while(carry) {
int now = res[p] - '0' + carry;
carry = now / 10;
res[p] = (now % 10) + '0';
p += 1;
}
}


while(res.back() == '0') res.pop_back();
reverse(begin(res), end(res));
return res;
}
string Solution::solve(int A) {
string res = "1";
for(int i = 2; i <= A; i++) res = mul(res, to_string(i));
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/02/PS/interviewbit/large-factorial/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.