[Jobdu] 题目1016:火星A+B

匿名 (未验证) 提交于 2019-12-02 23:49:02
原文链接:http://www.cnblogs.com/easonliu/archive/2012/07/25/2608602.html

题目描述:

输入:

输出:

样例输入:
1,0 2,1 4,2,0 1,2,0 1 10,6,4,2,1 0 0

样例输出:
1,0,1 1,1,1,0 1,0,0,0,0,0

跟大数运算加法有点像,对于大数运算第一位都是10进制,在取值时,需要模10,在这里只要模上该位对应的素数就OK了。

先建一个30位的素数表,判断n是否素数时只需检查n是否能被1到sqrt(n)之间的素数整除,这些素数可以从表里取得。若n是素数则将其加到表里。

代码如下:

#include <iostream> #include <vector> #include <sstream> #include <cmath> #include <algorithm> using namespace std;  string A,B; int p[30]; vector<int> a,b,c;  void init(){     p[0] = 2; p[1] = 3; p[2] = 5;     int c = 3;     for(int i=6;c<30;i++){         bool flag = true;         for(int j=0;p[j]<=sqrt(i)+1;j++){             if(i%p[j]==0){                 flag = false;                 break;             }         }         if(flag){             p[c] = i; c++;         }     } }  void toInt(){     a.clear(); b.clear();     for(int i=0;i<A.length();i++){         if(A[i]==',') A[i]=' ';     }     for(int i=0;i<B.length();i++){         if(B[i]==',') B[i]=' ';     }     int v;     istringstream sina(A);     while(sina>>v){         a.push_back(v);     }     istringstream sinb(B);     while(sinb>>v){         b.push_back(v);     }     reverse(a.begin(),a.end());     reverse(b.begin(),b.end()); }  void getRes(){     c.clear();     int la = a.size();     int lb = b.size();     int v = 0, carry = 0;     for(int i=0;i<(la>lb?la:lb);i++){         if(i>=la){             v = b[i] + carry;         }         else if(i>=lb){             v = a[i] + carry;         }         else{             v = a[i] + b[i] + carry;         }         c.push_back(v%p[i]);         carry = v/=p[i];         if(i==(la>lb?la:lb)-1&&carry!=0){             c.push_back(carry);         }     }     reverse(c.begin(),c.end());     for(int i=0;i<c.size();i++){         if(i==c.size()-1){             cout<<c[i]<<endl;             break;         }         cout<<c[i]<<",";     } }  int main(int argc,char* argv[]){     init();     while(cin>>A>>B&&A!="0"&&B!="0"){         toInt();         getRes();     }     return 0; } 

  

转载于:https://www.cnblogs.com/easonliu/archive/2012/07/25/2608602.html

文章来源: https://blog.csdn.net/weixin_30892889/article/details/96539453
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!