注意调整进位。
#include <stdio.h> #include <string.h> #include <math.h> #include <string> using namespace std; char a[1000]; char b[1000]; char c[1000]; int prime[] = { 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,101,103 }; void add() { int ia, ib; int la, lb; int i; int bit; int temp; la = strlen(a); lb = strlen(b); int tla = la - 1, tlb = lb - 1; int cIndex; int bIndex; bIndex = 0; bit = 0; cIndex = 0; while (tla >= 0 || tlb >= 0) { ia = 0; if (tla >= 0) { if (',' == a[tla]) tla--; i = 0; while (a[tla] != ',' && tla >= 0) { ia = pow(10, i++)*(a[tla] - '0') + ia; tla--; } } ib = 0; if (tlb >= 0) { if (',' == b[tlb]) tlb--; i = 0; while (b[tlb] != ',' && tlb >= 0) { ib = pow(10, i++)*(b[tlb] - '0') + ib; tlb--; } } temp = ia + ib + bit; if (temp >= prime[bIndex]) { bit = 1; temp = temp - prime[bIndex]; } else { bit = 0; } if (0 == temp) { c[cIndex++] = '0'; c[cIndex++] = ','; } else { while (temp != 0) { c[cIndex++] = (temp % 10) + '0'; temp = temp / 10; } c[cIndex++] = ','; } bIndex++; } if (0 != bit) { temp = bit; while (temp != 0) { c[cIndex++] = (temp % 10) + '0'; temp = temp / 10; } c[cIndex++] = ','; } cIndex = cIndex - 2; for (i = cIndex; i >= 0; i--) { if ('0' == c[i]) { printf("0"); continue; } printf("%c", c[i]); } printf("\n"); } //void getPrime() //{ // int i; // int j; // int count = 0; // int prime[27]; // int flag; // i = 1; // // while (count < 27) // { // i++; // flag = 0; // for (j = 2; j <= sqrt(i); j++) // { // if (0 == i%j) // { // flag = 1; // break; // } // } // // if (!flag) // { // prime[count] = i; // count++; // } // } // // for (i = 0; i < 27; i++) // printf("%d,", prime[i]); //} int main() { // getPrime(); while (1) { memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); memset(c, 0, sizeof(c)); scanf("%s %s", &a, &b); if (0 == strcmp(a, "0") && 0 == strcmp(b, "0")) break; add(); } return 0; }