(High-precision) multiplication and division to large numbers in C ++

Foreword

Last article, we achieved (precision) of large numbers of addition and subtraction, then we have achieved together large numbers under multiplication and division, because the algorithm is relatively simple, ordinary four algorithms similar to our primary school.

Multiplication and division have achieved here is a large number of multiply an int type integer (except).

Here is the code.

Code

#include <iostream>
#include <vector>

using namespace std;
//乘法
vector<int> mul(vector<int> &A, int b)
{
    vector<int> C;//结果数组
    int t=0;
    for(int i=0;i<A.size()||t;i++)
    {
        if(i<A.size()) t+=A[i]*b;
        C.push_back(t%10);
        t/=10;
    }
    return C;
}
//除法
vector<int> div(vector<int> &A,int b,int &k)
{
    vector<int> C;//保存商
    k=0;//保存余数
    for(int i=A.size()-1;i>=0;i--)
    {
        k=k*10+A[i];
        C.push_back(k/b);
        k%=b;
    }
    while(C.size()>=1&&C.front()==0) C.erase(C.begin());//消除前导0
    return C;
}

int main()
{
    string a,op;
    vector<int> A;
    int b;
    cin >> a >> op >> b;
    for(int i=a.size()-1;i>=0;i--) A.push_back(a[i]-'0');
    if(op=="mul")
    {
        auto C = mul(A,b);
        cout << "积:";
        for(int i=C.size()-1;i>=0;i--) printf("%d",C[i]);
    }
    if(op=="div")
    {
        int k=0;
        auto C = div(A,b,k);
        cout << "商:";
        for(auto c:C) cout << c;
        if(k!=0)
            cout << " 余: " << k <<endl;
    }
    return 0;
}

Input and output test

Input # 1

99999999 mul 1234

Output # 1

积:123399998766

Input # 2

10000000000000 div 9

Output # 2

商:1111111111111 余: 1

More you can visit my personal blog: a much blame

Published 17 original articles · won praise 4 · Views 9492

Guess you like

Origin blog.csdn.net/cyd1474003568/article/details/104819197