- /*题目描述:
- 读入两个不超过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
- 样例输出:
- 1,0,1
- 1,1,1,0
- 1,0,0,0,0,0
- */
- #include <cstdio>
- #include <iostream>
- #include <string.h>
- #include <cmath>
- using namespace std;
- bool check(int a) // Is it a prime number?
- {
- int i;
- for(i=2;i<=sqrt(a);i++)
- {
- if(a%i==0)
- break;
- }
- if(i>sqrt(a))
- return true;
- else
- return false;
- }
- int main()
- {
- int su[26]; //for storing the prime numbers
- int a[30],b[30],c[30]; //a+b
- char str[200];
- int i=0,j,s,t;
- int num=2;
- int len_a,len_b,len;
- // freopen("f:/in.txt","r",stdin);
- while(i<25)
- {
- if(check(num))
- {
- su[i]=num;
- i++;
- }
- num++;
- }//save the prime number to array
- while(gets(str))
- {
- memset(a,0,sizeof(a));
- memset(b,0,sizeof(b));
- memset(c,0,sizeof(c));
- len_a=len_b=0;
- len=strlen(str);
- for(i=0,s=0;i<len;i++)
- {
- if(str[i]==',')
- {
- s++;
- continue;
- }
- if(str[i]==' ')
- {
- j=++i;
- break;
- }
- a[s]=10*a[s]+str[i]-'0';
- } // 读入A
- for(t=0;j<len;j++)
- {
- if(str[j]==',')
- {
- // printf("%d",b[t]);
- t++;
- continue;
- }
- if(str[j]=='\n')
- break;
- b[t]=10*b[t]+str[j]-'0';
- } // 读入B
- if(a[0]==0 && b[0]==0)
- break;
- for(i=0;s>=0 && t>=0 ;s--,t--,i++) //A+B
- {
- c[i+1]=(a[s]+b[t]+c[i])/su[i];
- c[i]=(a[s]+b[t]+c[i])%su[i];
- }
- while(s>=0)
- {
- c[i+1]=(a[s]+c[i])/su[i];
- c[i]=(a[s]+c[i])%su[i];
- i++;
- s--;
- }
- while(t>=0)
- {
- c[i+1]=(b[t]+c[i])/su[i];
- c[i]=(b[t]+c[i])%su[i];
- i++;
- t--;
- } //end of A+B
- if(c[i]!=0) // output the first number
- printf("%d",c[i--]);
- else
- {
- printf("%d",c[--i]);
- i--;
- }
- while(i>=0)
- printf(",%d",c[i--]);
- printf("\n");
- }//end of output
- // fclose(stdin);
- return 0;
- }
火星 A+B问题(研究生复试题)
最新推荐文章于 2024-08-01 15:33:13 发布