洛谷 P1303:A*B Problem(高精度×高精度)

​【题目来源】
https://www.luogu.com.cn/problem/P1303

【题目描述】
给出两个非负整数,求它们的乘积。

【输入格式】
输入共两行,每行一个非负整数。

【输出格式】
输出一个非负整数表示乘积。

【数据范围】
每个非负整数不超过 10^2000。

【输入样例】
2
3

【输出样例】
6

【算法分析】
● 之前,在博客 https://blog.csdn.net/hnjzsyjyj/article/details/109219640 中给出过一种高精度×低精度的代码,本文是高精度×高精度的代码。
● 一个 n 位十进制数,一个 m 位十进制数,满足:n+m-1≤乘积位数≤n+m
● 当然,若如 https://www.acwing.com/problem/content/description/3126/ 题目所给的更大规模的数据,可考虑采用快速傅里叶变换(FFT)来求解。

【算法代码】

#include <bits/stdc++.h>
using namespace std;

const int maxn=4e3+5;
int a[maxn],b[maxn];
int c[maxn];

void hiMul(string s1,string s2) {
    int n=s1.size(),m=s2.size();
    for(int i=0; i<n; i++) a[i]=s1[n-1-i]-'0';
    for(int i=0; i<m; i++) b[i]=s2[m-1-i]-'0';

    for(int i=0; i<n; i++)
        for(int j=0; j<m; j++)
            c[i+j]+=a[i]*b[j];

    for(int i=0; i<n+m; i++) {
        c[i+1]+=c[i]/10;
        c[i]%=10;
    }

    int len=n+m+1;
    while(len>1 && c[len-1]==0) len--;

    for(int i=len-1; i>=0; i--) cout<<c[i];
    cout<<endl;
}

int main() {
    string s1,s2;
    cin>>s1>>s2;
    hiMul(s1,s2);

    return 0;
}

/*
in:
6
3

out:
18
*/




【参考文献】
https://www.acwing.com/blog/content/277/



 

​

posted @ 2026-10-03 06:59  Triwa  阅读(30)  评论(0)    收藏  举报