高精度乘法

高精度乘法

// An highlighted block
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
const ll mo = 10000;  // 位数与所压位数一定要统一, 1000 会WA
ll a[3][6006], cnt[100], w1[6002];
int n;
string s;

void init()
{
    for (int i=1; i<=2; i++){
        cin>>s;
        int t = 0;
        int base = 1;
        for (int j=s.length()-1; j>=0; j--){
            t++;
            a[i][(t-1)/4 + 1] = a[i][(t-1)/4 + 1] + base * (s[j] - '0'); 
            // - 1 除后 再 + 1 相当于改变值域
            base *= 10;
            if (base == 10000) base = 1;
        }
        cnt[i] = (s.length() % 4 == 0) ? (s.length() / 4) : (s.length() / 4 + 1);   
    }

}

void work()
{
    int cnt1 = 0;
    int cnt2 = 0;
    for (int i=1; i<=5001; i++) w1[i] = -1;
    for (int i=1; i<=cnt[1]; i++){
        for (int j=1; j<=cnt[2]; j++){
            w1[i+j-1] = (w1[i+j-1] == -1) ? a[1][i] * a[2][j] : w1[i+j-1] + a[1][i] * a[2][j];
        }  //判定 -1 随时都要小心
    }
    int t = 0;
    while (w1[t+1] != -1) {
        t++;
        if (w1[t] / mo > 0)
            w1[t+1] = (w1[t+1] == -1) ? w1[t]/mo : w1[t+1] + (w1[t] / mo);
        w1[t] %= mo;
    } cnt1= t;

    cout<<w1[cnt1]; 
    for (int i=cnt1-1; i>=1; i--) {
        int b = 0;
        ll p = w1[i];
        while (p) {
            b++, p/=10;
        }
        for (int j=1; j<=4-b; j++) cout<<0;
        cout<<w1[i]; 
    }
}

int main()
{
    init(); 
    work(); 
}

你可能感兴趣的:(高精度乘法)