题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1230
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13833 Accepted Submission(s): 4769
Problem Description
读入两个不超过25位的火星正整数A和B,计算A+B。需要注意的是:在火星上,整数不是单一进制的,第n位的进制就是第n个素数。例如:地球上的10进制数2,在火星上记为“1,0”,因为火星个位数是2进制的;地球上的10进制数38,在火星上记为“1,1,1,0”,因为火星个位数是2进制的,十位数是3进制的,百位数是5进制的,千位数是7进制的……
Input
测试输入包含若干测试用例,每个测试用例占一行,包含两个火星正整数A和B,火星整数的相邻两位数用逗号分隔,A和B之间有一个空格间隔。当A或B为0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即火星表示法的A+B的值。
Sample Input
1,0 2,1
4,2,0 1,2,0
1 10,6,4,2,1
0 0
Sample Output
1,0,1
1,1,1,0
1,0,0,0,0,0
------------------------------------------------------------
思路
模拟题。首先是要写一个辅助程序计算前25个素数,然后就是模拟进制加法。加法的过程类似百练 大整数的加减乘除(C++高精度)
------------------------------------------------------------
代码
#include
#include
#include
const int P[25] = { 2, 3, 5, 7,11,13,17,19,23,29,
31,37,41,43,47,53,59,61,67,71,
73,79,83,89,97};
char s1[105], s2[105];
int a1[30], a2[30];
int b[30];
int n1, n2, nb; // 加数和结果的位数
void solve()
{
int i = 0, len1 = strlen(s1), len2 = strlen(s2), num = 0, cnt = 0, dig;
for (i=0; i= '0' && dig <= '9')
{
dig = dig - '0';
num = num * 10 + dig;
}
else if (dig == ',')
{
a1[cnt++] = num;
num = 0;
}
}
a1[cnt++] = num;
n1 = cnt;
num = 0;
cnt = 0;
for (i=0; i= '0' && dig <= '9')
{
dig = dig - '0';
num = num * 10 + dig;
}
else if (dig == ',')
{
a2[cnt++] = num;
num = 0;
}
}
a2[cnt++] = num;
n2 = cnt;
}
void cal()
{
int i = 0, s = 0, si = 0;
for (i = 0; i < std::min(n1, n2); i++)
{
s = a1[n1-1-i] + a2[n2-1-i] + si;
b[i] = s%P[i];
si = s/P[i];
}
if (n1 > n2)
{
for (i = n2; i < n1; i++)
{
s = a1[n1-1-i] + si;
b[i] = s % P[i];
si = s / P[i];
}
}
else
{
for (i = n1; i < n2; i++)
{
s = a2[n2-1-i] + si;
b[i] = s % P[i];
si = s / P[i];
}
}
if (si > 0)
{
b[i] = si;
nb = i + 1;
}
else
{
nb = i;
}
}
void numprint()
{
int i = 0;
if (nb == 1)
{
printf("%d\n", b[0]);
}
else
{
for (i=nb-1; i>0; i--)
{
printf("%d,", b[i]);
}
printf("%d\n", b[0]);
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("hdu1230.txt", "r", stdin);
#endif
while (1)
{
scanf("%s%s", s1, s2);
solve();
if (n1 == 1 && n2 == 1 && a1[0] == 0 && a2[0] == 0)
{
break;
}
cal();
numprint();
}
return 0;
}