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 0Sample Output
1,0,1 1,1,1,0 1,0,0,0,0,0 個人感想 這道題測試了很多次,忘掉等號開以及字符數組太小等問題浪費了時間 source http://acm.hust.edu.cn/vjudge/contest/view.action?cid=89340#problem/D#include <stdio.h>
#include <math.h>
#include <string.h>
int prime(int x)
{
int flag = 1;
for(int i = 2; i <= sqrt(x); i++)
{
if(x % i == 0)
{
flag = 0;
break;
}
}
return flag;
}
int main()
{
int p[30], top = 0, len1, len2, num1[30], num2[30], ans[30];
char str1[1000], str2[1000];
for(int i = 2; top < 25; i++)
{
if(prime(i))
{
p[top++] = i;
//printf("%d\n\n", p[top-1]);
}
}
while(~scanf("%s%s", str1, str2))
{
if(strcmp(str1, "0") == 0 || strcmp(str2, "0") == 0)
break;
memset(num1, 0, sizeof(num1));
memset(num2, 0, sizeof(num2));
memset(ans, 0, sizeof(ans));
top = 0;
int k = 1, cnt;
len1 = strlen(str1);
len2 = strlen(str2);
/*for(int i = 0; i < len1; i++)
{
printf("%c:%c\n", str1[i], str2[i]);
}
printf("\n\n"); */
//printf("len1 = %d len2 = %d\n", len1, len2);
for(int i = len1 - 1; i >= 0; i--)
{
if(str1[i] == ',')
{
top++;
k = 1;
continue;
}
num1[top] += (str1[i] - '0') * k;
//printf("i = %d : num1[%d] = %d\n\n", i, top, num1[top]);
k = k*10;
}
cnt = top+1;
//printf("cnt = %d\n", cnt);
top = 0;
k = 1;
for(int i = len2 - 1; i >= 0; i--)
{
if(str2[i] == ',')
{
top++;
k = 1;
continue;
}
num2[top] += (str2[i] - '0') * k;
//printf("i = %d : num2[top] = %d\n\n", i, top, num2[top]);
k = k*10;
}
if(top+1 > cnt)
cnt = top+1;
//printf("cnt = %d\n", cnt);
for(int i = 0; i < cnt; i++)
{
ans[i] += num1[i] + num2[i];
while(ans[i] >= p[i] && p[i] != 0)
{
ans[i+1] += ans[i] / p[i];
ans[i] %= p[i];
}
//printf("ans[%d] = %d, num1[%d] = %d, num2[%d] = %d\n", i, ans[i], i, num1[i], i, num2[i]);
k = i+1;
}
if(ans[k])
printf("%d,", ans[k]);
for(int i = cnt-1; i > 0; i--)
printf("%d,", ans[i]);
printf("%d\n", ans[0]);
}
}