Code
package com.wangyou;
import java.util.*;
public class FindPrime {
public static void main(String[] args) throws Exception {
ArrayList<Integer> primes = findPrimes3(400, 800);
for(int i : primes) {
System.out.println(i);
}
}
private static ArrayList<Integer> findPrimes1(int start, int end) {
ArrayList<Integer> primes = new ArrayList<Integer>();
for(int i = start; i <= end; i++) {
if(isPrime1(i)) {
primes.add(i);
}
}
return primes;
}
private static ArrayList<Integer> findPrimes2(int start, int end) {
ArrayList<Integer> primes = new ArrayList<Integer>();
for(int i = start; i <= end; i++) {
if(isPrime2(i)) {
primes.add(i);
}
}
return primes;
}
private static ArrayList<Integer> findPrimes3(int start, int end) {
ArrayList<Integer> primes = new ArrayList<Integer>();
BitSet b = new BitSet(end + 1);
for(int i = 2; i * i <= end; i ++) {
if(!b.get(i)) {
for(int j = i + i; j <= end; j += i) {
b.set(j);
}
}
}
for(int i = start; i <= end; i ++) {
if(!b.get(i)) {
primes.add(i);
}
}
return primes;
}
private static boolean isPrime1(int n) {
for(int i = 2; i * i <= n; i++)
if(n % i == 0)
return false;
return true;
}
private static boolean isPrime2(int n) {
int divisor = 3;
int testLimit = n;
if(n % 2 == 0)
return false;
while(testLimit > divisor)
{
if(n % divisor == 0)
return false;
testLimit = n / divisor;
divisor += 2;
}
return true;
}
}
package com.wangyou;
import java.util.*;
public class FindPrime {
public static void main(String[] args) throws Exception {
ArrayList<Integer> primes = findPrimes3(400, 800);
for(int i : primes) {
System.out.println(i);
}
}
private static ArrayList<Integer> findPrimes1(int start, int end) {
ArrayList<Integer> primes = new ArrayList<Integer>();
for(int i = start; i <= end; i++) {
if(isPrime1(i)) {
primes.add(i);
}
}
return primes;
}
private static ArrayList<Integer> findPrimes2(int start, int end) {
ArrayList<Integer> primes = new ArrayList<Integer>();
for(int i = start; i <= end; i++) {
if(isPrime2(i)) {
primes.add(i);
}
}
return primes;
}
private static ArrayList<Integer> findPrimes3(int start, int end) {
ArrayList<Integer> primes = new ArrayList<Integer>();
BitSet b = new BitSet(end + 1);
for(int i = 2; i * i <= end; i ++) {
if(!b.get(i)) {
for(int j = i + i; j <= end; j += i) {
b.set(j);
}
}
}
for(int i = start; i <= end; i ++) {
if(!b.get(i)) {
primes.add(i);
}
}
return primes;
}
private static boolean isPrime1(int n) {
for(int i = 2; i * i <= n; i++)
if(n % i == 0)
return false;
return true;
}
private static boolean isPrime2(int n) {
int divisor = 3;
int testLimit = n;
if(n % 2 == 0)
return false;
while(testLimit > divisor)
{
if(n % divisor == 0)
return false;
testLimit = n / divisor;
divisor += 2;
}
return true;
}
}