[JAVA] 质数表源码

打印2~MAX中所有的质数


// Demo1.java
package info.tozzger.demo;

import java.util.BitSet;

public class Demo1 {

	protected final static int MAX = 1000;
	protected static BitSet bs = new BitSet(MAX - 1);

	public static void main(String[] args) {
		for (int num = 2; num <= MAX; num++) {
			if (bs.get(getPosition(num)))
				continue;
			if (!isPrime(num)) {
				for (int j = 1; j * num <= MAX; j++) {
					bs.set(getPosition(j * num));
				}
			}
		}
		for (int num = 2, rn = 0; num <= MAX; i++) {
			if (!bs.get(getPosition(num))) {
				System.out.printf("%d\t", num);
				if ((++rn) == 5) {
					System.out.println();
					rn = 0;
				}
			}
		}
	}

	protected static int getPosition(int num) {
		return num - 2;
	}

	protected static boolean isPrime(int num) {
		if (num < 2)
			return false;
		if (num == 2)
			return true;
		int max = (int) Math.sqrt(num);
		for (int i = 2; i <= max; i++) {
			if (num % i == 0)
				return false;
		}
		return true;
	}
}

发表评论