String + array to simulate the multiplication of large Integers

Source: Internet
Author: User

String + array to simulate the multiplication of large Integers

There are Precision Problems in C/C ++, and it is difficult to add and multiply large integers. Here we provide a simulated Multiplication operation for large integers.

Simulation Principle:

Simulate the multiplication of the values of each bit and add it to the corresponding position. Finally, ensure that the number of each bit is smaller than 10, that is, scanning the carry from the end to the header.

Main Code:


K = (mx-I) + (mbx-j); // position after Multiplication
C [k-1] + = sum % 10;
C [k] + = sum/10;

For (t = 1; t <= k; ++ t) {// ensure that the number of each bit is smaller than 10
If (c [t]> = 10 ){
// Cout < <<" ";
C [t + 1] + = c [t]/10;
C [t] = c [t] % 10;
}
} <<">


Tested code:

/**
* The character string is multiplied by a large integer.
*/
# Include
# Include
# Include
Using namespace std;
Int c [1001];
Int main ()
{
String a, B;
While (cin> a> B ){
// Memset (c, 0, sizeof (c ));
For (int I = 0; I <= 1000; I ++) c [I] = 0;
Int mx = a. size ();
Int mbx = B. size ();
Int ma = mx-1;
Int mb = mbx-1;
Int k, t;
For (int I = ma; I> = 0; -- I ){
For (int j = mb; j> = 0; -- j ){
Int sum = (B [j]-'0') * (a [I]-'0 ');
// Cout < <
K = (mx-I) + (mbx-j );
C [k-1] + = sum % 10;
C [k] + = sum/10;
}
}
If (! C [k]) -- k;
For (t = 1; t <= k; ++ t ){
If (c [t]> = 10 ){
// Cout < <<" ";
C [t + 1] + = c [t]/10;
C [t] = c [t] % 10;
}
}
If (c [t + 1]) k = t + 1;
For (t = k; t> = 1; t --){
Cout <
}
Cout <
}
Return 0;
}




<<"> <

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.