数组模拟乘法(大数乘法)

A * B Problem

Input

Each line contain two integers A and B. Procss to end of file.(EOF)

Output

For each case, Please output the value of A multiply B

Sample Input 1

3 2
1 5

Sample Output 1

6
5

思路:

用小学数学的乘法的方法,代码如下:

#include<stdio.h>
#include<string.h>
int main()
{
    char arr1[101],arr2[101];
    int a[101],b[101],c[201],i,j,k;
    while(scanf("%s%s",&arr1,&arr2)!=EOF)
    {
        int n=strlen(arr1);
        int m=strlen(arr2);
        k=n+m;//俩数相乘小于俩数的位数相加
        memset(c,0,sizeof(c));//数组初始化
        for(i=0;i<n;i++)a[i]=arr1[n-1-i]-'0';//数倒序储存到另一个数组
        for(i=0;i<m;i++)b[i]=arr2[m-1-i]-'0';
        for(i=0; i<n; i++)
            for(j=0; j<m; j++)
                c[i+j]+=a[i]*b[j],c[i+j+1]+=c[i+j]/10,c[i+j]=c[i+j]%10;//相乘和进位
        i=k;
        while(c[i]==0&&i>0)i--;//去掉前导
        for(;i>=0;i--)printf("%d",c[i]);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43328040/article/details/84823009