唉,小曹从医可惜了,他的兴趣全在算法上
重剑无锋,大巧不工
//水仙花数 //21位 #include <stdio.h> #include <time.h> #define N 10 const int Pow[10][21] = {{0}, {1}, {2, 5, 1, 7, 9, 0, 2}, {3, 0, 2, 3, 5, 3, 0, 6, 4, 0, 1}, {4, 0, 1, 1, 1, 5, 6, 4, 0, 8, 9, 3, 4}, {5, 2, 1, 3, 0, 2, 8, 5, 1, 7, 3, 8, 6, 7, 4}, {6, 5, 8, 7, 7, 3, 0, 4, 6, 0, 5, 9, 6, 3, 9, 1, 2}, {7, 0, 0, 4, 8, 2, 3, 8, 0, 4, 6, 8, 5, 4, 5, 8, 5, 5}, {8, 0, 8, 5, 7, 7, 4, 5, 8, 6, 3, 0, 2, 7, 3, 3, 2, 2, 9}, {9, 0, 2, 9, 5, 3, 2, 1, 5, 1, 3, 1, 9, 8, 9, 8, 1, 4, 9, 0, 1}}; void narciss (); void add (int *, int); void sub (int *sum, const int num); void SumNumber (int *sum, int * pstack); int cmp (int *a, int *b); int main () { clock_t start, end; int n = 1; start = clock (); narciss (); end = clock (); printf ("%.3lfs\n", (double)(end - start) / CLK_TCK); return 0; } void narciss () { int iSumNum[N] = {0}; int iStackNum[N] = {0}; int iSum[22] = {0}; int iStack[22] = {0}; int *top = iStack; int * const maxTop = iStack + 21; int flag = 0; int k = 9; int i; while (1) { if (top < maxTop && iSum[21] == 0) { add (iSum, k); *top++ = k; iStackNum[k]++; } if (iSum[21] > 0) { sub (iSum, k); iStackNum[k]--; top--; k = *top - 1; } if (top == maxTop) { if (0 == iSum[20]) break; SumNumber (iSum, iSumNum); if (cmp (iSumNum, iStackNum)) { for (i = 20; i >= 1; i--) printf ("%d", iSum[i]); printf ("\n"); } if (0 != *(top - 1)) { sub (iSum, k); iStackNum[k]--; } else { while (0 == *(top - 1)) { top--; iStackNum[0]--; } flag = 1; } k = *--top; if (flag) { sub (iSum, k); iStackNum[k]--; flag = 0; } k--; } } } void add (int *sum, const int num) { int i; // const int j = num * 21; for (i = 0; i < 21; i++) sum[i] += Pow [num][i]; for (i = 0; i < 21; i++) { if (sum[i] > 9) { sum[i + 1] += sum[i] / 10; sum[i] = sum[i] % 10; } } } void sub (int *sum, const int num) { int i; for (i = 0; i < 21; i++) { if (sum[i] < Pow[num][i]) { sum[i + 1] -= 1; sum[i] = sum[i] + 10 - Pow[num][i]; } else { sum[i] -= Pow[num][i]; } } } void SumNumber (int *sum, int * pstack) { int len = 21; memset (pstack, 0, sizeof (int) * N); while (len--) { pstack[*sum++]++; } } int cmp (int *a, int *b) { int i; for (i = 0; i < N; i++) if (a[i] != b[i]) return 0; return 1; }刚完成,太笨了,用了一个下午的时间,求21位的水仙花数用12秒多,还有改进的空间。