回溯实现素数环
import java.util.*; public class Prime { public static void main(String arg[]) { int t,i,j,k,s,n,count=0; int[] a=new int[2000]; int[] b=new int[1000]; Scanner input=new Scanner(System.in); n=input.nextInt(); for(k=1;k<=2*n;k++) b[k]=0; for(k=3;k<=2*n;k+=2){ for(t=0,j=3;j<=Math.sqrt(k);j+=2) if(k%j==0){ t=1;break; } if(t==0) b[k]=1; } System.out.println("8项素数和环:"); a[1]=1;s=0; i=2;a[i]=2; while(true){ t=1; count++; for(j=1;j<i;j++) if(a[j]==a[i]||b[a[i]+a[i-1]]!=1){ t=0;break; } if(t==1&&i==n&&b[a[n]+1]==1){ s++; System.out.print(s+":1"); for(j=2;j<=n;j++) System.out.print(","+a[j]); System.out.println(""); } if(t==1&&i<n) {i++;a[i]=2;continue;} while(a[i]==n&&i>1) i--; if(i>1) a[i]++; else break; } System.out.println("循环次数"+count); } }