LoginSignup
1
0

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-12-03

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

ルール

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

プログラム(Java)

Composite.java
class Composite{
    public static void main(String[] args){
        int in = Integer.parseInt(args[0]);
        int num = 4;
        int sum = 0;
        int composites = 0;
        while(composites < in){
            if(!Composite.isPrime(num)){
                composites++;
                sum += num;
            }
            num++;
        }
        System.out.println(sum);
    }

    public static boolean isPrime(int n){
        if(n < 2)return false;
        if(n == 2)return true;
        if(n % 2 == 0)return false;
        for(int i=3; i*i<=n; i+=2){
            if(n % i == 0)return false;
        }
        return true;
    }
}

コンパイル

$ javac Composite.java

出力例

$ java Composite 2
10
$ java Composite 4
27
$ java Composite 10
112
$ java Composite 100
7059

メモ

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

1
0
2

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