Product
| Product |
The Problem
The problem is to multiply two integers X, Y. (0<=X,Y<10250)
The Input
The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.
The Output
For each input pair of lines the output line should consist one integer the product.
Sample Input
12 12 2 222222222222222222222222
Sample Output
144 444444444444444444444444
题目解析:
输入两个整数X, Y. (0<=X,Y<10250),求两个整数的积。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int MAX = 1000;
void getDigits(int num[],char str[])//把字符串保存在int类型的数组中
{
char digit;
int len = strlen(str);
for(int i=0;i<len;++i) {
digit=str[i];
num[len-i-1]=digit-'0';//字符串倒叙保存
}
}
void multiply(int a[],int b[],int sum[])
{
/*
数组a和数组b逐位相乘,并把结果保存于数组sum
12345*12345 5与12345中的每位相乘
对于数组sum sum[i+j]在i=0,j=1,2,3,4,5时保存的是5和各位相乘的结果
而在i=1,j=1,2,3,4,5时保存的是4和各位相乘的结果,并累加上次相乘的结果
*/
for(int i=0;i<MAX;i++) {
for(int j=0;j<MAX;j++) {
sum[i+j] += a[i]*b[j];
}
}
/*将十位以上的数字向上进位
*将剩余的数字保存在自己位置上
* /
for(int i=0;i<MAX*2-1;i++)
{
sum[1+i] += sum[i]/10;
sum[i] = sum[i]%10;
}
}
int main()
{
char num1[MAX],num2[MAX];
int a[MAX];
int b[MAX];
int sum[MAX*2];
while(scanf("%s%s",&num1,&num2)!=EOF)
{
if(strcmp(num1,"0")==0||strcmp(num2,"0")==0) {
printf("0\n");
continue;
}
getchar();
memset(a,0,sizeof(a)); //初始化数组a,b
memset(b,0,sizeof(b));
memset(sum,0,sizeof(sum));
getDigits(a,num1);
getDigits(b,num2);
multiply(a,b,sum);
int j=MAX*2-1;
while(sum[j]==0) {
j--;
}
for(int i = j;i >= 0;i--) {
printf("%d",sum[i]);
}
printf("\n");
}
return 0;
}
本文介绍了一种处理大整数乘法的方法,通过将字符串形式的大整数转换为数组,然后采用逐位相乘的方式实现两个大整数的乘法运算。此方法适用于超出常规整型变量表示范围的大整数计算。
741

被折叠的 条评论
为什么被折叠?



