標籤:c++ oj stl acm 大數
來源: http://acm.hdu.edu.cn/showproblem.php?pid=1230
火星A+B
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10562 Accepted Submission(s): 3524
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,14,2,0 1,2,01 10,6,4,2,10 0
Sample Output
1,0,11,1,1,01,0,0,0,0,0
Source浙大電腦研究生複試上機考試-2006年
題意: 略
題解: 大數問題。用一個數組ans 存放各個數位的進位,兩個數組N1 N2分別儲存兩個火星數。在編程實現方面,主要是開頭的輸入需要一點技巧。
AC代碼:
#include<iostream>#include<cstring>#include<cmath>#include<cstdio>using namespace std;bool prime(int k){if(k==2||k==3)return true;for(int i=2;i<=(int)sqrt(float(k));i++)if(k%i==0) return false;return true; }const int Max=55;int num1[Max],num2[Max],N1[Max],N2[Max],posx=0,posy=0,temp; int ans[60+5];char ch;int main(){int tpos=0;for(int i=2;tpos<56;i++)if(prime(i)) ans[tpos++]=i;while(1){posx=0,posy=0;memset(N1,0,sizeof(N1)); memset(N2,0,sizeof(N2));while(1){scanf("%d",&temp);ch=getchar();num1[posx++]=temp;if(ch==' ')break;}while(1){scanf("%d",&temp);ch=getchar();num2[posy++]=temp;if(ch=='\n')break;}//posx++; posy++;if((posx==1&&!num1[0])||(posy==1&&!num2[0]))return 0; for(int i=posx-1;i>=0;i--) N1[posx-i-1]=num1[i]; for(int i=posy-1;i>=0;i--) N2[posy-i-1]=num2[i]; for(int i=0;i<Max-2;i++){ N1[i]+=N2[i]; if(N1[i]>=ans[i]){ N1[i+1]++;N1[i]%=ans[i]; } } int k; for(k=Max-3;k>0&&!N1[k];)k--; for(;k>0;k--) printf("%d,",N1[k]); printf("%d\n",N1[0]);}}