素数环:n个自然数排成环形,使得每相邻两个数之和为素数,构成素数环。
为了巩固队列,做了一下,书上的算法不全,没有判断首元素与最后一个元素之和是否为素数,不能生成多种素数环。
看了博客,粘贴代码,发现如果要完全解决,用到队列的知识(不用回溯解决),其中有递归算法,可能要遍历时用到“二叉树深度遍历”,先放上代码,学好二叉树的知识之后,再来理解。
1 public interface Queue<T> { // 队列接口 2 public abstract boolean isEmpty(); 3 4 public abstract boolean add(T x); 5 6 public abstract T peek(); 7 8 public abstract T poll(); 9 10 }
1 public class LinkedQueue<T> implements Queue<T> { 2 private Node<T> front, rear; 3 4 public LinkedQueue() { 5 this.front = this.rear = null;// 构造空队列 6 } 7 8 public boolean isEmpty() { 9 return this.front == null && this.rear == null; 10 } 11 12 public boolean add(T x) { 13 if (x == null) 14 return false; 15 Node<T> q = new Node<T>(x, null); 16 if (this.front == null) 17 this.front = q; 18 else 19 this.rear.next = q; 20 this.rear = q; 21 return true; 22 } 23 24 public T peek() { 25 return this.isEmpty() ? null : this.front.data; 26 } 27 28 public T poll() { 29 if (isEmpty()) 30 return null; 31 T x = this.front.data; 32 this.front = this.front.next; 33 if (this.front == null) 34 this.rear = null; 35 return x; 36 } 37 38 } 39 // 素数环类 40 public class PrimeRing { 41 public boolean isPrime(int number) { // 判断一个数是否为素数 42 if (number == 2) 43 return true; 44 for (int i = 2; i < Math.sqrt(number) + 1; i++) { 45 if (number % i == 0) 46 return false; 47 } 48 return true; 49 } 50 51 public SeqList<Integer> insertRing(SeqList<Integer> L, 52 LinkedQueue<Integer> Q, int index, int total) { 53 // 从第index个数开始进行遍历 54 int count = 0; // 记录遍历队列中数据元素的个数 55 while (!Q.isEmpty() && count <= total - index) {// 每个元素都遍历一遍 56 57 int p = (Integer) Q.poll();// 队列出队 58 int q = (Integer) L.get(L.size() - 1); 59 60 if (index == total) { // 队尾元素 61 if (isPrime(p + q) && isPrime(p + 1)) { 62 L.insert(p); // 插入到顺序表表尾 63 return L; 64 } else { 65 Q.add(p); 66 } 67 } else if (isPrime(p + q)) {// 如果未遍历到最后一个元素 68 L.insert(p); 69 if (insertRing(L, Q, index + 1, total) != null) {// 递归 70 return L; 71 } 72 L.remove(L.size() - 1);// 移除顺序表表尾数据元素 73 Q.add(p); 74 } else { 75 Q.add(p); 76 } 77 ++count; 78 } 79 return null; 80 } 81 82 public SeqList<Integer> makePrimeRing(int n) { 83 SeqList<Integer> L = new SeqList<Integer>(n); 84 L.insert(1); // 初始化顺序表的首结点为1 85 LinkedQueue<Integer> Q = new LinkedQueue<Integer>(); 86 for (int i = 2; i <= n; i++) { 87 Q.add(i);// 初始化队列 88 } 89 return insertRing(L, Q, 2, n); 90 91 } 92 93 public static void main(String[] args) { 94 PrimeRing pr = new PrimeRing(); 95 SeqList<Integer> L = pr.makePrimeRing(10); 96 for (int i = 0; i < L.size(); i++) { 97 System.out.print(L.get(i) + " "); 98 } 99 100 } 101 102 }