正文

大数相乘的一种高效算法2006-04-01 14:31:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/vfdff/11725.html

分享到:

/**************************************    算法复杂度为:O(longhta*longthb)    longtha为乘数的位数    longhtb为被乘数的位数***************************************/#include <stdio.h>#include <string.h>#include <conio.h>#define LEN 1000void mult(char [],char [],char []);main(){    char op1[LEN],op2[LEN],op3[LEN*2-1];    scanf("%s%s",op1,op2);    mult(op1,op2,op3);    printf("%s\n",op3);    getch();    return 0;   }    void reverse(char a[]){    int longth=strlen(a);    int i;    for(i=0;i<longth/2;i++){        char t;        t=a[i];        a[i]=a[longth-i-1];        a[longth-i-1]=t;    }}void mult(char op1[LEN],char op2[LEN],char ans[LEN*2-1]){    char top1[LEN];    char top2[LEN];    strcpy(top1,op1);    strcpy(top2,op2);    reverse(top1);    reverse(top2);    int k;    int top1s=strlen(top1);    int top2s=strlen(top2);    for(k=0;k<top1s+top2s;k++){        ans[k]='0';    }    int i,j;    int jw,ys;    int longth;    for(j=0;j<top2s;j++){        jw=0;        for(i=0;i<top1s;i++){            ys=((top1[i]-'0')*(top2[j]-'0')+jw+ans[i+j]-'0')%10;            jw=((top1[i]-'0')*(top2[j]-'0')+jw+ans[i+j]-'0')/10;            ans[i+j]=ys+'0';        }        if(jw>0){            ans[i+j]=jw+'0';        }    }    longth=i+j-1;    if(jw>0)        ans[longth++]=jw+'0';    ans[longth]='\0';    reverse(ans);}    

阅读(10671) | 评论(12)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

loading...
您需要登录后才能评论,请 登录 或者 注册