【题目来源】
https://www.luogu.com.cn/problem/P1303
【题目描述】
给出两个非负整数,求它们的乘积。
【输入格式】
输入共两行,每行一个非负整数。
【输出格式】
输出一个非负整数表示乘积。
【数据范围】
每个非负整数不超过 10^2000。
【输入样例】
2
3
【输出样例】
6
【算法分析】
之前,在博客 https://blog.csdn.net/hnjzsyjyj/article/details/109219640 中给出过一种高精度×低精度的代码,本文是高精度×高精度的代码。
当然,若如 https://www.acwing.com/problem/content/description/3126/ 题目所给的更大规模的数据,可考虑采用快速傅里叶变换(FFT)来求解。
【算法代码】
- #include
- using namespace std;
-
- const int maxn=1e5+5;
- int a[maxn],b[maxn];
- int ans[maxn];
- string s1,s2;
- int k;
-
- int main() {
- cin>>s1>>s2;
- int lena=s1.length();
- int lenb=s2.length();
- for(int i=1; i<=lena; i++) a[i]=s1[lena-i]-'0';
- for(int i=1; i<=lenb; i++) b[i]=s2[lenb-i]-'0';
-
- int x=lena+lenb;
- for(int i=1; i<=lena; i++) {
- for(int j=1; j<=lenb; j++) {
- ans[i+j-1]+=a[i]*b[j];
- if(ans[i+j-1]>=10) {
- ans[i+j]+=ans[i+j-1]/10;
- if(i+j-1==x) x++;
- ans[i+j-1]%=10;
- }
- }
- }
-
- for(int i=x; i>=1; i--) {
- if(k==0 && ans[i]==0) continue; //去除前导0
- else {
- cout<
- k++;
- }
- }
- if(k==0) cout<<0;
-
- return 0;
- }
-
-
- /*
- input:
- 12 3
- output:
- 36
- */