任意の数より小さいすべての素数のアルゴリズムを求めます


package org.basic.test;

import java.util.ArrayList;
import java.util.List;

public class TestPrimer {

	public static void main(String[] args) {
		int scope = 5000000;
		System.out.println("scope=" + scope);
		TestPrimer tp = new TestPrimer();
		long time1 = System.currentTimeMillis();
		List<Integer> primers1 = tp.getPrime1(scope);
		long time2 = System.currentTimeMillis();
		List<Integer> primers2 = tp.getPrime2(scope);
		long time3 = System.currentTimeMillis();
		System.out.println("     :" + (time2 - time1) + " ms");
		System.out.println(primers1.size());
		//tp.print(primers1);
		System.out.println("     :" + (time3 - time2) + " ms");
		System.out.println(primers2.size());
		//tp.print(primers2);
	}
	
	public void print(List<Integer> primers){
		for(Integer i : primers){
			System.out.print(i + ", ");
		}
	}

	public List<Integer> getPrime1(int number) {
		List<Integer> primes = new ArrayList<Integer>();
		primes.add(2);
		for (int i = 3; i <= number; i++) {
			if (isPrime1(primes, i)) {
				primes.add(i);
			}
		}
		return primes;
	}

	//  i    i        i    。
	public boolean isPrime1(List<Integer> primes, int i) {
		for (int prime : primes) {
			if(prime * prime > i){
				return true;
			}
			if (i % prime == 0) {
				return false;
			}
		}
		return true;
	}

	public List<Integer> getPrime2(int number) {
		List<Integer> primes = new ArrayList<Integer>();
		primes.add(2);
		for (int i = 3; i <= number; i++) {
			if (isPrime2(i)) {
				primes.add(i);
			}
		}
		return primes;
	}
	
	public boolean isPrime2(int i) {
		for (int j = 2; j < Math.sqrt(i) + 1; j++) {
			if (i % j == 0) {
				return false;
			}
		}
		return true;
	}  

}


scope=5000000
     :2953 ms
348513
     :7031 ms
348513