火星A+B
时间限制(普通/Java):3000MS/10000MS 运行内存限制:65536KByte
总提交:54 测试通过:18
总提交:54 测试通过:18
描述
读入两个不超过25位的火星正整数A和B,计算A+B。需要注意的是:在火星上,整数不是单一进制的,第n位的进制就是第n个素数。例如:地球上的10进制数2,在火星上记为“1,0”,因为火星个位数是2进制的;地球上的10进制数38,在火星上记为“1,1,1,0”,因为火星个位数是2进制的,十位数是3进制的,百位数是5进制的,千位数是7进制的……
输入
测试输入包含若干测试用例,每个测试用例占一行,包含两个火星正整数A和B,火星整数的相邻两位数用逗号分隔,A和B之间有一个空格间隔。当A或B为0时输入结束,相应的结果不要输出。
输出
对每个测试用例输出1行,即火星表示法的A+B的值。
样例输入
1,0 2,1
4,2,0 1,2,0
1 10,6,4,2,1
0 0
4,2,0 1,2,0
1 10,6,4,2,1
0 0
样例输出
1,0,1
1,1,1,0
1,1,1,0
1,0,0,0,0,0
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include<string>
using std::string;
#include<sstream>
using std::istringstream;
#include<cstdlib>
#define BIT_MAX_NUMBER 26
int prime[BIT_MAX_NUMBER];
void makePrimesBasedNumber(int primes[], const unsigned int number){
unsigned int current = 2u;
primes[0] = 2; primes[1] = 3;
for (int i = 5; current < number; i += 2){
bool flag = true;
for (int j = 1; primes[j] * primes[j] <= i; ++j){
if (i%primes[j] == 0){ flag = false; break; }
}
if (flag){ primes[current++] = i; }
}
}
void printMarsNumber(const int* n){
size_t pos = 0;
while (n[pos] == 0){
++pos;
}
cout << n[pos];
++pos;
while (pos != BIT_MAX_NUMBER){
cout << ',' << n[pos];
++pos;
}
cout << endl;
}
void split(int* array, const string& str){
istringstream sin(str);
char comma;
memset(array, 0, BIT_MAX_NUMBER * sizeof(int));
sin >> array[BIT_MAX_NUMBER - 1];
while (sin >> comma){
for (size_t ix = 0; ix != BIT_MAX_NUMBER - 1; ++ix){
array[ix] = array[ix + 1];
}
sin >> array[BIT_MAX_NUMBER - 1];
}
}
void add(const int* a, const int* b, int* c){
int carry = 0;
for (size_t ix = BIT_MAX_NUMBER - 1; ix != 0; --ix){
int ans = a[ix] + b[ix] + carry;
c[ix] = ans%prime[BIT_MAX_NUMBER - 1 - ix];
carry = ans/prime[BIT_MAX_NUMBER - 1 - ix];
}
c[0] = carry;
}
int main(void){
makePrimesBasedNumber(prime, BIT_MAX_NUMBER);
string a, b;
int marsA[BIT_MAX_NUMBER];
int marsB[BIT_MAX_NUMBER];
int sum[BIT_MAX_NUMBER];
while (cin >> a >> b, a.length() != 1 || b.length() != 1 || a[0] != '0' || b[0] != '0'){
split(marsA, a);
split(marsB, b);
add(marsA, marsB, sum);
printMarsNumber(sum);
}
return EXIT_SUCCESS;
}