0
0

【JavaScript】paizaラーニング問題集 素数の個数

Posted at

こちらの問題を解きました。

  • 言語はJavaScriptを選択(解答コード例なし)
  • 解答コード例C++、Python3の方針とは別解
    単純に判定対象の整数より小さいすべての数で割って割り切れたらfalseとした。
回答
process.stdin.resume();
process.stdin.setEncoding('utf8');
var lines = [];
var reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});
reader.on('line', (line) => {
    lines.push(line);
});
reader.on('close', () => {

    const N = parseInt(lines[0]);        // 入力値取得
    const pn = [];                       // 素数格納用

    // 2からNまで調べる
    for (let num=2; num<=N; num++){
        let flg = true;

        // 2から自分自身-1までの数で割る
        for (let divisor=2; divisor<num; divisor++){
            if(num % divisor == 0){
                flg = false;
                break;
            }
        }

        if (flg){
            pn.push(num);
        }
    }

    console.log(pn.length);
    
});
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