C language, multiplication of two large integers

  For the integer shaping, it is int, long int, long long int. The range is as follows:

Types of Number of bytes Representation range
int 4 -2147483648~+2147483647
long int 4 -2147483648~2147483647
long long int 16 -9223372036854775808~+9223372036854775807

  But in some cases, long long int can't be used to express. In this case, the array representation should be used. The overall calculation method is consistent with the manual calculation sequence. Each digit of the number A is multiplied by the number B and then added (note that each digit of the number A must be multiplied by 10). When doing the addition, the carry relationship must be handled well.
  The source code is as follows:

#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<fstream>
using namespace std;

void bigNumMul(long int x,long int y)
{
    
    
	int a[64] = {
    
    0};
	int b[64] = {
    
    0};
	int c[64] = {
    
    0};
    long t;
	if(x<y)  // 保证x是大的那一个 
	{
    
    
		t = x;
		x = y;
		y = t; 
	} 
	long m = x;
	int a_num = 0;
    //把x每位数分别存入数组
    for(int i=0; i<64; i++)
	{
    
    
		a[i] = m%10;
		a_num++;
		m = m / 10;
		if(m == 0)
			break;
	}

	long n = y;
	int b_num = 0;
    //把y每位数分别存入数组
	for(int i=0; i<64; i++)
	{
    
    
		b[i] = n%10;
		b_num++;
		n = n/10;
		if(n == 0)
			break;
	}
        
    //中间数的存放位为num+1
	const int _a_num=a_num+1;
	vector<int>mid_val; // 最好使用vector, 静态整形数组还是有长度限制,空间可能会爆 
	for(int i=0;i<_a_num;i++)
	{
    
    
		mid_val.push_back(0);
	}
    
    // 乘法操作 
	for(int i=0; i<b_num; i++)
	{
    
       int backAdd = 0;//backAdd为乘积的进位数
		// 一位乘一行 
		for(int j=0; j<=a_num; j++)
		{
    
    
			int product = a[j]*b[i];//两个位数乘积
			int sum = product + backAdd;
			mid_val[j] = sum%10;
			backAdd=sum/10;
		}
		// 一行加一行 
        backAdd = 0;//一行积的一位与另一行积的一位相加的进位数
		for(int k=i; k<=i+a_num; k++) // 从i开始是为了符合,乘法每高位依次向左移 
		{
    
    
			int sum = c[k] + mid_val[k-i] + backAdd;
			c[k] = sum % 10;
			backAdd = sum / 10;
		}
	}

	// 放入是是倒叙放入,查找的时候也需要倒着 
	int startBit=0;
	for(int i=63;i>=0;i--)
	{
    
    
		if(c[i]!=0)
		{
    
    
			startBit=i;
			break;
		}
	}
	for(int i=startBit;i>=0;i--)
	{
    
    
		cout<<c[i];
	}
}

int main(void)
{
    
    
	bigNumMul(2147483647,2147483647);
	return 0;
} 

Reference blog:

https://blog.csdn.net/tsinfeng/article/details/5939395

https://blog.csdn.net/xcrazyu/article/details/87879103

Guess you like

Origin blog.csdn.net/gls_nuaa/article/details/114682250