High precision multiplication
High precision multiplication refers to the multiplication of large integers that cannot be represented by ordinary data types (such as longint).
step
High precision multiplication mainly includes the following requirements and processes
1. In order to obtain the value of each bit of the input number, including bits, tens, etc., the input integer data cannot be satisfied. Therefore, the input data must be in the form of string.
2. Convert the string to integer type, and store each bit value in the array
3. High precision multiplication, focus! Carry calculation is carried out by simulating the manual calculation method of human.
4. Integer to string display
Code
The following code can be run directly in the community version of vs2015, with comments on key steps
#include <iostream> using namespace std; #define Length 100 int *Muiti(int *a, int *b ,int la, int lb) { int i, j,*c; int len; len = la + lb; c = (int *)malloc((len) * sizeof(int)); memset(c, 0, sizeof(int)*len); /*The key point of high-precision multiplication is to calculate the value of each bit of the result by the carry method according to the way of manual multiplication*/ for (i = 0; i<la; i++)//Each bit of the integer a is multiplied by all bits of b respectively for (j = 0; j < lb; j++) { c[i + j] += a[i] * b[j];//Add the product of the i-th bit of a and the j-th bit of b to the position of c[i+j] c[i + j + 1] += c[i + j] / 10;//Carry in next position c[i + j] = c[i + j] % 10;//Keep the remainder after dividing by 10 in the current position } return c; } int *Str2int(char *str) { int len,i; int *num; len = strlen(str); num = (int *)malloc(len * sizeof(int)); memset(num, 0, len * sizeof(int)); for (i = 0; i < len; i++)//Store each character in reverse order num[i] = str[len - i - 1] - '0';//Subtract with ASCII value and convert to integer return num; } char *Int2str(int *num,int len) { int i, j; char *res; res = (char *)malloc(len * sizeof(char)); memset(res, 0, len * sizeof(char)); while (num[len-1] == 0 && len>1)//Multiplying two numbers, the number of resulting digits must be less than or equal to the sum of the two digits { //The sum of digits greater than or equal to - 1 len--; } for (i = 0; i < len; i++)//Add in ASCII value and convert to multiply string form { res[i] = num[len - 1 - i] + '0'; } return res; } void main() { char *s1, *s2,*s; int *a, *b, *c; int i,la, lb,len; s1 = (char *)malloc(Length * sizeof(char));//When using pointers, you need to allocate memory first s2 = (char *)malloc(Length * sizeof(char)); memset(s1, 0, sizeof(char)*(Length));//Initialize allocated memory, set to 0 memset(s2, 0, sizeof(char)*(Length)); cin >> s1 >> s2; la = strlen(s1);//Count string length, excluding end '\ 0' lb = strlen(s2); len = la + lb; a = Str2int(s1);//Character to integer b = Str2int(s2); c=Muiti(a, b, la, lb);//Key point: high precision multiplication s = Int2str(c,len);//Integer to character cout << s << endl; }