【經典演算法問題】素數環問題
阿新 • • 發佈:2019-01-22
/* 素數環問題 2014-4-8 17:22:28 */ #include <stdio.h> #include <math.h> #include <string.h> bool hasSelected[21]; int site[21]; bool checkPrime(int k){ if(k < 2) return 0; for(int i = 2; i <= sqrt(k); ++i) if(k % i == 0) return 0; return 1; } void print(){ for(int i = 1; i < 21; ++i) printf("%d ", site[i]); printf("\n"); } void backTrack(int k){ if(k == 21){ if(checkPrime(site[20] + site[1])) print(); return; } int i, j; for(i = k; i < 21; ++i){ for(j = 1; j < 21; ++j) if(!hasSelected[j] && checkPrime(j + site[k - 1])){ site[k] = j; hasSelected[j] = 1; backTrack(k + 1); hasSelected[j] = 0; } } } int main(){ //freopen( "data.out", "w", stdout ); site[1] = 1; hasSelected[1] = 1; backTrack(2); return 0; }