High-precision multiplication Orsay One Pass T1307

Topic link

[Title description] Enter two high-precision positive integers M and N (both M and N are less than 100 digits). Find the product of these two high precision numbers.
[Input] Input two high-precision positive integers M and N.
[Output] Find the product of these two high-precision numbers.
【Input sample】

36
3

[Sample output]

108

The lengths of M and N are far greater than the scope of int, we need to store these two large numbers in strings, and manually simulate the multiplication process.
I think the difficulty is the position of the string in the simulation process, because the high bits of M and N after reading are the 0 subscript of the string, and the final storage result is the low bit stored in the 0 subscript of the string.
One set of test arrays is far from enough. It is recommended to test and test data such as 99×9 9999×99 1000×10 10×1000 85695×5 6×26522 after writing the code. If it can pass, it will probably be no problem.
To simulate the process of multiplication, I multiply the first number with the second number from low to high and store the results in the same sum (result) string. Pay attention to the handling of cases where there is a carry when multiplied to the last digit.

#include<iostream>
#include<cstdio>
using namespace std;
int sum[500]={
    
    0};
string m,n;
void cheng(int i,int x)
{
    
    
	int last1=0;
	int last2=0;
	int ex;
	int now=0;
	for(int j=m.length()-1;j>=0;j--)
	{
    
    
		now=(x*(m[j]-'0')+last1)%10;
		last1=(x*(m[j]-'0')+last1)/10;
		
		ex=(last2+now+sum[i+m.length()-j-1])/10;
		sum[i+m.length()-j-1]=(last2+now+sum[i+m.length()-j-1])%10;
		last2=ex;
	}
	sum[i+m.length()]+=(last1+last2);
}
int main()
{
    
    
	cin>>m;
	cin>>n;
	for(int i=n.length()-1;i>=0;i--)
	{
    
    
		cheng(n.length()-i-1,n[i]-'0');
	}
	int i=499;
	while(sum[i]==0)
	i--;
	while(i>=0)
	{
    
    
		printf("%d",sum[i]);
		i--;
	}
	printf("\n");
	return 0;
}

Guess you like

Origin blog.csdn.net/Huo6666/article/details/113000448