1. 程式人生 > >Java資料結構:素數環(將1~n個自然數排列成環形,使得每相鄰兩數之和為素數)

Java資料結構:素數環(將1~n個自然數排列成環形,使得每相鄰兩數之和為素數)



public class 素數環 {
	public boolean isPrime(int num) {	//判斷是否為素數
		if (num == 1) {
			return false;
		}
		Double n = Math.sqrt(num);
		for (int i = 2; i <= n.intValue(); i++) {		//平方根
			if (num % i == 0) {
				return false;
			}
		}
		return true;
	}

	public MyList makePrimeRing(int n) throws Exception {	//求n個正整數的素數環,並以順序返回
		if (n % 2 != 0) {
			throw new Exception("素數環不存在");
		}
		MyList L = new MyList(n);				
		L.insert(0, 1);
		LinkQueue Q = new LinkQueue();
		for (int i = 2; i <= n; i++) {
			Q.offer(i);
		}
		return insertRing(L, Q, 2, n);
	}

	public MyList insertRing(MyList L, LinkQueue Q, int m, int n)
			throws NumberFormatException, Exception {
		int count = 0;
		while (!Q.isEmpty() && count <= n - m) {				//佇列非空
			int p = (Integer) Q.poll();
			int q = (Integer) L.get(L.length() - 1);	
			if (m == n) {				//如果是最後一位
				if (isPrime(p + q) && isPrime(p + 1)) {
					L.insert(L.length(), p);
					return L;
				} else {
					Q.offer(p);
				}
			} else if (isPrime(p + q)) {	//如果不少最後一位
				L.insert(L.length(), p);
				if (insertRing(L, Q, m + 1, n) != null) {
					return L;
				}
				L.remove(L.length() - 1);
				Q.offer(p);
			} else {
				Q.offer(p);
			}
			++count;
		}
		return null;
	}
	public static void main(String[] args) throws Exception {
		素數環 a=new 素數環();
		MyList L=a.makePrimeRing(10);
		for(int i=0;i<L.length();i++){
			System.out.println(L.get(i)+" ");
		}
	}
}