经典DP,写的可能麻烦了一些。
#include <stdio.h> #define false 0 #define true 1 int is_prime[41]; int is_visit[21]; int sequence[21]; void DFS(int, int, int); int main() { int i, j, k; int n; is_prime[1] = false; is_prime[2] = true; for (i=2; i<=40; i++) { k = 0; for (j=2; j*j<=i; j++) { if (i%j == 0) { k = 1; break; } } if (k) { is_prime[i] = false; } else { is_prime[i] = true; } } k = 0; while (scanf("%d", &n) != EOF) { printf("Case %d: ", ++k); DFS(1, 1, n); printf(" "); } return 0; } void DFS(int num, int order, int end) { int i; is_visit[num] = true; sequence[order] = num; if (order == end) { if (is_prime[num+1]) { sequence[order] = num; for (i=1; i<=end; i++) { if (i != end) printf("%d ", sequence[i]); else printf("%d ", sequence[i]); } } } else { for (i=1; i<=end; i++) { if (is_visit[i] == false && is_prime[i+num]) { DFS(i, order+1, end); is_visit[i] = false; } } } }