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)+" ");
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42192693/article/details/82502604