Question

I wrote this code to work with big integer:
the sum function work correctly but the multiple function doesn't work.
Can anyone help me to fix my problem?

Était-ce utile?

La solution

To me it looks you are storing the numbers least-significant digit first. Then this last loop looks it should iterate the opposite way, i.e. from the first - least significant digit, and add the remander to Mul[i+1] rather then Mul[i+1].

for(int i=m;i>0;i--)
{
    if(Mul[i]>9)
    {
        Mul[i-1]+=Mul[i]/10;
        Mul[i]%=10;
    }
}

That would however still not be enough, since even the last digit, Mul[m], can still get more than 9, therefore you need to continue past it.

Your code can be however made much simpler.

Mul[i+j]+=(Num1[i]*Num2[j]+temp)%10;
temp=(Num1[i]*Num2[j]+temp)/10;

After doing this, you are possibly laving Mul[i+j] more than 9, therefore needing the (now failing) post-processing. You can change this to take the remainder from the whole sum, hence leaving Mul[i+j] always less than 10.

void mul() {
    int s1 = c1.size(), s2 = c2.size();
    for (i = 0; i < s1; ++i) {
        int temp = 0;
        // note the condition - this ensures the cycle continues past i+s2
        // as long as there is some remainder (assumes same length of Num2 and Mul)
        for (j = 0; j < s2 || temp != 0; ++j) {
            // add the current multiple and the remainder to the digit
            Num[i + j] += Num1[i] * Num2[j] + temp;
            // take the remainder from the whole sum, not only the added part
            // this way Mul[i + j] < 10, therefore you don't need any postprocess
            temp = Mul[i + j] / 10;
            Num[i + j] %= 10;
        }
    }
}

Moreover, you don't need to store the remander in temp, you can directly add it to Mul[i+j+1], it will be taken care in the next iteration anyway.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top