自己写的方法。
#include <iostream> #include <cstdio> #include <vector> #include <stack> using namespace std; int prime[25]; void getPrime(){ prime[0] = 2; int num = 1; for(int i = 3; num < 25; i++){ bool flag = true; for(int j = 2; j < i; j++){ if(i % j == 0){ flag = false; break; } } if(flag){ prime[num] = i; num++; } } } stack<int> getNum(string s){ stack<int> res; int i = 0; int num = 0; while(i <= s.length()){ while(s[i] != ',' && i != s.length()){ num = num * 10 + s[i] - '0'; i++; } if(s[i] == ',' || i == s.length()){ res.push(num); num = 0; i++; } } return res; } int main(){ string a, b; getPrime(); //vector<int> ; stack<int> num1, num2, ans; while(cin >> a >> b){ int t = 0; if(a == "0" || b == "0") return 0; num1 = getNum(a); num2 = getNum(b); int carry = 0; while(!num1.empty() && !num2.empty()){ int tmp = num1.top() + num2.top() + carry; ans.push(tmp % prime[t]); carry = tmp / prime[t]; t++; num1.pop(); num2.pop(); } while(!num1.empty()){ int tmp = num1.top() + carry; carry = tmp / prime[t]; ans.push(tmp % prime[t]); t++; num1.pop(); } while(!num2.empty()){ int tmp = num2.top() + carry; carry = tmp / prime[t]; ans.push(tmp % prime[t]); t++; num2.pop(); } if(carry != 0){ ans.push(carry); } printf("%d", ans.top()); ans.pop(); while(!ans.empty()){ printf(",%d", ans.top()); ans.pop(); } printf("\n"); } }