62,614
社区成员
发帖
与我相关
我的任务
分享
package com.yaowei.algorithm;
import java.util.ArrayList;
public class ArrayPrime {
public void arrayPrime() {
int[] resultArray = new int[20];
StringBuffer result = new StringBuffer();
boolean []arrayFlag = new boolean[20];
for(int i=0;i<resultArray.length;i++) {
resultArray[i] = 0;
}
for(int i=0;i<arrayFlag.length;i++) {
//全部没有被选择
arrayFlag[i] = true;
}
//把首位置为1
resultArray[0] = 1;
arrayFlag[0] = false;
result.append(1+" ");
int locationIndex = 1;
int totalCount =0;
while(locationIndex > 0) {
int temp = findNextPrime(resultArray[locationIndex-1],resultArray[locationIndex],arrayFlag);
if(temp == 0) {
if(resultArray[locationIndex]!=0) {
arrayFlag[resultArray[locationIndex]-1] = true;
}
resultArray[locationIndex] = 0;
locationIndex--;
}else {
if(resultArray[locationIndex]!=0) {
arrayFlag[resultArray[locationIndex]-1] = true;
}
resultArray[locationIndex] = temp;
locationIndex++;
arrayFlag[temp-1] = false;
}
if(locationIndex == 20) {
locationIndex--;
//20个数都排满了,检查下
if(this.isPrimeNum(resultArray[19]+1)) {
totalCount++;
System.out.println("gg"+locationIndex+java.util.Arrays.toString(resultArray));
}
}
}
System.out.println(totalCount);
}
public int findNextPrime(int a,int b1,boolean []b) {
int start;
if(a%2==0) {
start = 1;
}else {
start = 2;
}
for(int i=start;i<21;i=i+2) {
if(this.isPrimeNum(i+a)&&b[i-1]&&(a!=i)&&i>b1) {
return i;
}
}
return 0;
}
public static void main(String []args) {
ArrayPrime a = new ArrayPrime();
a.arrayPrime();
}
boolean isPrimeNum(int i)
{
if(i<2) return false;
if(i==2||i==3) return true;
if(i%2==0) return false;
int temp = (int)Math.sqrt(i)+1;
for (int j = 2; j < temp; j++)
{
if (i % j == 0)
{
return false;
}
}
return true;
}