两个很大的数相乘

#include <iostream>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
const int maxN=200;
char s1[maxN],s2[maxN];
int a[maxN],b[maxN];
int **ans=new int*[maxN];
int ret[2*(maxN+1)];
int main()
{
    int len1,len2,i,j,k,k1,k2,num,sum,over;
    while(scanf("%s%s",s1,s2)!=EOF)
    {
        len1=strlen(s1);
        len2=strlen(s2);
        k1=0;
        for(i=len1-1; i>=0; i-=4)
        {
            sum=0;
            for(j=i; j>i-4&&j>=0; j--)
            {
                num=s1[j]-'0';
                for(k=i-j; k>0; k--)
                    num*=10;
                sum+=num;
            }
            a[k1++]=sum;
        }
        k2=0;
        for(i=len2-1; i>=0; i-=4)
        {
            sum=0;
            for(j=i; j>i-4&&j>=0; j--)
            {
                num=s2[j]-'0';
                for(k=i-j; k>0; k--)
                    num*=10;
                sum+=num;
            }
            b[k2++]=sum;
        }

        /*
        for(i=k1-1; i>=0; i--)
            cout<<a[i]<<" ";
        cout<<endl;
        for(i=k2-1; i>=0; i--)
            cout<<b[i]<<" ";
        cout<<endl;
        */
        for(i=0; i<maxN; i++)
        {
            ans[i]=new int[2*(maxN+1)];
            memset(ans[i],0,sizeof(int)*2*(maxN+1));
        }
        for(i=0; i<k1; i++)
        {
            over=0;
            k=i;//expansion 10^(4*i)
            for(j=0; j<k2; j++,k++)
            {
                ans[i][k]=a[i]*b[j]+over;
                over=ans[i][k]/10000;
                ans[i][k]%=10000;
            }
            if(over)
                ans[i][k]=over;
        }
        /*
        for(i=0; i<k1; i++)
        {
            for(j=2*(maxN+1)-1; j>=0; j--)
                if(ans[i][j])
                    break;
            if(j==-1)
            {
                printf("0\n");
                continue;
            }
            printf("i= %d , j= %d , ans[i][j] = %d\n",i,j,ans[i][j]);
            for(j-=1; j>=0; j--)
                printf("%04d",ans[i][j]);
            printf("\n");
        }
        */
        memset(ret,0,sizeof(ret));
        for(i=0; i<k1; i++)
        {
            over=0;
            for(j=0; j<2*(maxN+1); j++)
            {
                ret[j]+=ans[i][j]+over;
                over=ret[j]/10000;
                ret[j]%=10000;
            }
        }
        for(i=2*(maxN+1)-1; i>=0; i--)
            if(ret[i])
                break;
        if(i==-1)
        {
            printf("0\n");
            continue;
        }
        printf("%d",ret[i]);
        for(i-=1; i>=0; i--)
        {
            printf("%04d",ret[i]);
        }
        printf("\n");
    }
    return 0;
}

 

posted @ 2015-10-01 11:29  myth_HG  阅读(442)  评论(0编辑  收藏  举报