📄 primesearch.java
字号:
package primecruncher;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupFactory;import net.jxta.exception.PeerGroupException;import java.util.List;import java.util.ArrayList;import java.util.Iterator;import java.util.Set;/** * PrimeSearch finder. This program produces a list of prime numbers between 1 and a * given integer. */public class PrimeSearch { public static int numPrimes(int from, int to) { return findPrimes(from, to).length; } public static int[] findPrimes(int from, int to) { if (from > to) { throw new IllegalArgumentException("First number must be smaller than the second."); } int[] list; //create an array containing all integers between the two specified numbers list = new int[to - from + 1]; for (int i = 0; i < list.length; i++) { list[i] = from++; } //find out the module for each item in list, divided by each d, where //d is < or == to sqrt(to) //if the remainder is 0, the nubmer is a composite, and thus //we mark its position with 0 in the marks array, //otherwise the number is a prime, and thus mark it with 1 //int maxDiv = (int)Math.sqrt(to); int maxDiv = (int)Math.sqrt(to); int[] mark = new int[list.length]; for (int i=0; i < list.length; i++) { for (int z=2; z < maxDiv; z++) { if (list[i] != z && (list[i] % z == 0)) { mark[i] = 1; } } } //create new array that contains only the primes, and return that array int primes = 0; for (int i=0; i < mark.length; i++) { if (mark[i] == 0) { primes++; } } int[] ret = new int[primes]; int curs = 0; for (int i=0; i < mark.length; i++) { if (mark[i] == 0) { ret[curs] = list[i]; curs++; } } return ret; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -