LoginSignup
2
1

More than 5 years have passed since last update.

合成数列の和アドベントカレンダー JavaScript 編

Last updated at Posted at 2018-12-04

合成数列の和アドベントカレンダー Advent Calendar 2018 の 5 日目です。

ルール

  • 入力として正の整数 N を与えたら 4 から始まる 合成数 の数列の 1 番目から N 番目からの合計を出力してください
  • N は最大で 100 とします

プログラム(JavaScript)

composite.js
function isPrime(n){
    if(n < 2)return false;
    if(n == 2)return true;
    if(n % 2 == 0)return false;
    for(let i=3; i*i<=n; i+=2){
        if(n % i == 0)return false;
    }
    return true;
}

let indata = process.argv[2];
let num = 4;
let composites = 0;
let sum = 0;
while(composites < indata){
    if(!isPrime(num)){
        composites++;
        sum += num;
    }
    num++;
}
console.log(sum);

出力例

$ node composite.js 2
10
$ node composite.js 4
27
$ node composite.js 10
112
$ node composite.js 100
7059

メモ

この問題は ずんだ問題 の番外編です

2
1
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
2
1