大数乘法

来源:互联网 发布:中国电信cn2网络 编辑:程序博客网 时间:2024/05/01 09:37
int main(){     string num1,num2;     // 初始状态用string来存储大数     cout<<"现在,来两个大数吧! "<<endl;     cin>>num1>>num2;     const char *p1=num1.c_str();    //将string转为 const char *     const char *p2=num2.c_str();    //将string转为 const char *     multiply(p1,p2);     return 0;}void multiply(const char *a,const char *b){      int i,j,ca,cb,*s;      ca=strlen(a);      cb=strlen(b);      s=(int *)malloc(sizeof(int)*(ca+cb));   //分配存储空间,两数相乘,结果最长为两数位数的长度和      for(i=0;i<ca+cb;i++)      s[i]=0;      // 每个元素赋初值0      for(i=0;i<ca;i++)          for (j=0;j<cb;j++)              s[i+j+1]+=(a[i]-'0')*(b[j]-'0');      for(i=ca+cb-1;i>=0;i--)        // 这里实现进位操作          if (s[i]>=10)          {              s[i-1]+=s[i]/10;              s[i]%=10;          }      char *c=(char *)malloc((ca+cb)*sizeof(char));  //分配字符数组空间,因为它比int数组省!      i=0;      while(s[i]==0) i++;   // 跳过头部0元素      for(j=0;i<ca+cb;i++,j++)      c[j]=s[i]+'0';      c[j]='\0';      for(i=0;i<ca+cb;i++)      cout<<c[i];      cout<<endl;      free(s);}
<pre name="code" class="cpp">#include "stdio.h" #include "stdlib.h"  #define M 100  typedef struct _Node{ int s[M]; int l; int c; }Node, *pNode;  void cp(pNode src, pNode des, int st, int l){ int i, j; for(i=st, j=0; i<st+l; i++, j++){ des->s[j] = src->s[i]; } des->l = l; des->c = st + src->c; }  /* 分治法 大数乘法 X = A*10^n + B Y = C*10^m + D X*Y = A*C*10^(n+m) + A*D*10^n + B*C*10^m + B*D */  void add(pNode pa, pNode pb, pNode ans){ int i, c; int ta, tb; pNode k;  if(pa->c < pb->c){ k = pa; pa = pb; pb = k; } ans->c = pb->c; c = 0; for(i=0; i<pa->l+pa->c-pb->c; i++){ if(i<pa->c-pb->c) ta = 0; else ta = pa->s[i-(pa->c-pb->c)]; if(i>=pb->l) tb = 0; else tb = pb->s[i]; ans->s[i] = (ta + tb + c)%10; c = (ta + tb + c)/10; } if(c) ans->s[i++] = 1; ans->l = i; }  void mul(pNode pa, pNode pb, pNode ans){ int i, c, w; int ma = pa->l>>1, mb = pb->l>>1; Node ah, al, bh, bl; Node t1, t2, t3, t4, z; pNode k;  if(!ma || !mb){ if(!ma){ k = pa; pa = pb; pb = k; }  ans->c = pa->c + pb->c; w = pb->s[0]; c = 0; for(i=0; i<pa->l; i++){ ans->s[i] = (w*pa->s[i] + c)%10; c = (w*pa->s[i] + c)/10; } if(c) ans->s[i++] = c; ans->l = i; return; }  cp(pa, &ah, ma, pa->l-ma); cp(pa, &al, 0, ma); cp(pb, &bh, mb, pb->l-mb); cp(pb, &bl, 0, mb);  mul(&ah, &bh, &t1); mul(&ah, &bl, &t2); mul(&al, &bh, &t3); mul(&al, &bl, &t4);  add(&t3, &t4, ans); add(&t2, ans, &z); add(&t1, &z, ans);  }  int main(){ Node ans; int i; //54321 * 543 Node a = {{1, 2, 3, 4, 5}, 5, 0}; Node b = {{3, 4, 5}, 3, 0}; mul(&a, &b, &ans); for(i=ans.l-1; i>=0; i--) printf("%d", ans.s[i]); printf("\n"); return 0; }



0 0
原创粉丝点击