Need help in a large problem

Revision en1, by clex, 2025-03-08 18:12:51

So I'm stuck with this problem: Given N, print 2 lines. The first line is the number of digits in N!. In the second line, if N! number of digits >=100 then print its first 100 digits, otherwise print N!. N<=10,000.

I was thinking of using bignum and recursion to find N! but got Time Limit Exceeded.

Thanks for helping me and sorry if you feel uncomfortable.

This is my code:

include <bits/stdc++.h>

using namespace std; string del0(const string &s) { int i = 0; while (i < s.size()-1 && s[i] == '0') i++; return s.substr(i); }

string SUM(string a, string b) { if(a.size() < b.size()) swap(a, b); while(b.size() < a.size()) b = "0" + b; string res = ""; int carry = 0; for (int i = a.size()-1; i >= 0; i--) { int sum = (a[i]-'0') + (b[i]-'0') + carry; res = char(sum % 10 + '0') + res; carry = sum / 10; } if(carry) res = char(carry + '0') + res; return del0(res); }

string DIF(string a, string b) { while(a.size() < b.size()) a = "0" + a; while(b.size() < a.size()) b = "0" + b; string res = ""; int carry = 0; for (int i = a.size()-1; i >= 0; i--) { int digitA = a[i] — '0'; int digitB = b[i] — '0'; int diff = digitA — digitB — carry; if(diff < 0) { diff += 10; carry = 1; } else { carry = 0; } res = char(diff + '0') + res; } return del0(res); }

string MUL(string a, string b) { a = del0(a); b = del0(b); int n = max(a.size(), b.size()); while(a.size() < n) a = "0" + a; while(b.size() < n) b = "0" + b;

if(n == 1)
    return to_string((a[0]-'0') * (b[0]-'0'));

int m = n / 2;
string a1 = a.substr(0, n - m);
string a0 = a.substr(n - m);
string b1 = b.substr(0, n - m);
string b0 = b.substr(n - m);

string z0 = MUL(a0, b0);
string z2 = MUL(a1, b1);
string sumA = SUM(a0, a1);
string sumB = SUM(b0, b1);
string z1 = MUL(sumA, sumB);
string mid = DIF(DIF(z1, z2), z0);
for (int i = 0; i < 2 * m; i++) z2.push_back('0');
for (int i = 0; i < m; i++) mid.push_back('0');

string result = SUM(SUM(z2, mid), z0);
return del0(result);

}

int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; string s = "1"; for (int i = 1; i <= n; i++){ s = MUL(s, to_string(i)); } s = del0(s); cout << s.size() << "\n"; if (s.size() > 100) cout << s.substr(0, 100); else cout << s;

return 0;

}

Tags need help, bignumber, large inputs

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English clex 2025-03-08 18:32:44 16
en2 English clex 2025-03-08 18:13:51 6
en1 English clex 2025-03-08 18:12:51 2741 Initial revision (published)