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?

素数を判定するのを作ってみよう!(番外編)

Last updated at Posted at 2024-10-15
function Is_prime(a){
    let prime_is = true;
    if(a == 1){
        prime_is = false;
    }else{
        for(let i = 2; i <= a - 1; i++){
            if(a % i == 0){
                prime_is = false;
            }
        }
    }
    return prime_is;
}

というプログラムを前回は書きました。

条件を変える

これをこうじゃ!

function Is_prime(a){
    let prime_is = true;
    if(a == 1){
        prime_is = false;
    }else{
        for(let i = 2; i < a; i++){ /*変わったのはここ*/
            if(a % i == 0){
                prime_is = false;
            }
        }
    }
    return prime_is;
}

i <= a - 1
はaより小さいことなので
i < aと書けます!

平方根

function Is_prime(a){
    let prime_is = true;
    if(a == 1){
        prime_is = false;
    }else{
        for(let i = 2; i < Math.sqrt(a) + 1; i++){ /*変わったのはここ*/
            if(a % i == 0){
                prime_is = false;
            }
        }
    }
    return prime_is;
}

平方根を使うことで処理を高速化しました!

即リターン

function Is_prime(a){
    if(a == 1){
        return false;
    }else{
        for(let i = 2; i < Math.sqrt(a) + 1; i++){
            if(a % i == 0){
                return false;
            }
        }
    }
    return true;
}

これでより高速化できました!

0
0
8

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?