0
0

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 3 years have passed since last update.

エラトステネスの篩

Last updated at Posted at 2021-10-01

#ソースコード

function primesvalue(n){
    // サイズnのブーリアン値trueを持つリストを作成
    let cache = [];
    for(let i = 0; i < n; i++) {
        cache.push(true);
    }

    // ステップを√n回繰り返します。
    for (let currentPrime = 2; currentPrime < Math.ceil(Math.sqrt(n)); currentPrime++){
        if (!cache[currentPrime]) continue;
        let i = 2;
        let ip = i * currentPrime;
        while (ip < n){
            cache[ip] = false;
            // i*pをアップデートします。
            i += 1;
            ip = i * currentPrime;
        }
    }

    // 素数
    let numbers = [];
    for (let i = 2; i < cache.length; i++){
        if (cache[i]){
            numbers.push(i);
        }
    }

    return numbers;
}

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?