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

合成数列の和Advent Calendar 2018

Day 6

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

Last updated at Posted at 2018-12-05

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

ルール

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

プログラム(Go)

composite.go
package main

import (
    "flag"
    "fmt"
)

func isPrime(n int) bool {
    if n < 2 {
        return false
    } else if n == 2 {
        return true
    } else if n % 2 == 0 {
        return false
    } else {
        for i := 3; i * i <= n; i += 2 {
            if n % i == 0 {
                return false
            }
        }
    }
    return true
}

func main() {
    indata := flag.Int("i", 0, "target value")
    flag.Parse()
    num := 4;
    composites := 0;
    sum := 0;
    for (composites < *indata) {
        if (!isPrime(num)) {
            composites++;
            sum += num;
        }
        num++;
    }
    fmt.Println(sum);
}

出力例

$ go run composite.go -i 2
10
$ go run composite.go -i 4
27
$ go run composite.go -i 10
112
$ go run composite.go -i 100
7059

メモ

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

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