Problem description:
Round the N integers from 1 to n into a ring. If any two adjacent numbers are added and the result is a prime number, the ring becomes a prime number ring.
AlgorithmDescription: Typical Deep Search problem.
Code:
# Include <iostream> using namespace STD; int n = 0; int data [30] = {0}; bool not_contain (INT num, int depth) {for (INT I = 0; I <= depth; I ++) {If (data [I] = num) {return false ;}} return true ;} bool is_prime (INT num) {int I = 2; while (I <= num/2) {If (Num % I = 0) {return false ;} I ++;} return true;} void print (INT depth) {Int J = 0; For (j = 0; j <= depth; j ++) {cout <data [J] <";}cout <Endl ;}void DFS (INT depth) {If (depth> 2 & is_prime (data [depth] + data [0]) {print (depth) ;}int I = 1; for (I = 1; I <= N; I ++) {If (is_prime (data [depth] + I) {If (not_contain (I, depth) {depth ++; data [depth] = I; DFS (depth); Data [depth] = 0; depth -- ;}}} int main () {n = 10; data [0] = 1; DFS (0); Return 0 ;}