6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Wikipediaの手順通りに「エラトステネスの篩」をJavaで書いてみた

Posted at
public static void main(String[] args) {
	List<Long> ansList = sieve(1000L);
	System.out.println(ansList.toString());
}

public static List<Long> sieve(Long x) {

	// 探索リストを作成
	LinkedList<Long> searchList = new LinkedList<Long>();
	for (Long i = 2L; i <= x; i++) {
		searchList.add(i);
	}

	// 素数リスト
	LinkedList<Long> primeNumberList = new LinkedList<Long>();

	// 探索リストの先頭要素がxの平方根に達するまで以下の処理を繰り返す
	while (searchList.getFirst() < Math.sqrt(x)) {

		// 探索リストの先頭要素を素数リストに追加する
		Long primeNumber = searchList.getFirst();
		primeNumberList.add(primeNumber);

		// 探索リストの先頭要素の倍数を探索リストから削除する
		for (Iterator<Long> it = searchList.iterator(); it.hasNext();) {
			if (it.next() % primeNumber == 0) {
				it.remove();
			}
		}
	}

	// 探索リストに残った数を素数リストに追加する
	primeNumberList.addAll(searchList);

	return primeNumberList;
}
6
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?