Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

埃氏篩法 Sieve of Eratosthenes #16

Open
shyangs opened this issue Aug 6, 2017 · 0 comments
Open

埃氏篩法 Sieve of Eratosthenes #16

shyangs opened this issue Aug 6, 2017 · 0 comments

Comments

@shyangs
Copy link
Owner

shyangs commented Aug 6, 2017

import java.util.*;

public class PrimeSieve {

	public static LinkedList<Integer> sieve(int n) {
		if (n < 2) { return new LinkedList<Integer>(); }

		LinkedList<Integer> primes = new LinkedList<Integer>();
		LinkedList<Integer> nums = new LinkedList<Integer>();

		// nums = [2, 3, 4, 5, 6, 7, ..., n]
		for (int i = 2; i <= n; i++) { 
			nums.add(i);
		}

		// 從 nums移除所有 2 的倍數, 把 2 放入primes
		// 從 nums移除所有 3 的倍數, 把 3 放入primes
		// 從 nums移除所有 5 的倍數, 把 5 放入primes
		// ...
		while (nums.size() > 0) {
			int nextPrime = nums.remove();
			for (int i = nextPrime * nextPrime; i <= n; i += nextPrime) {
				nums.removeFirstOccurrence(i);
			}
			primes.add(nextPrime);
		}
		return primes;
	}

	public static void main(String[] args) {
		System.out.println("Please input an integer: ");
		Scanner scanner = new Scanner(System.in);
		System.out.println( sieve( scanner.nextInt() ) );
		if (scanner != null) { scanner.close(); }
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant