1
1

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.

プロジェクトオイラーで学ぶJAVA8

1
Posted at

Java8で導入されたストリームAPIなどを勉強のためにプロジェクトオイラーの問題を解いてます。

問題1

10未満の自然数のうち, 3 もしくは 5 の倍数になっているものは 3, 5, 6, 9 の4つがあり, これらの合計は 23 になる.

同じようにして, 1000 未満の 3 か 5 の倍数になっている数字の合計を求めよ.

解答

わかりきったことですが、
1から999までループしながら3または5の倍数か判定しながら足していきます。

Java7までのコード

    public static int sum() {

        int sum = 0;

        for (int i = 1; i < 1000; i++) {

            if (i % 3 == 0 || i % 5 == 0) {
                sum += i;
            }
        }

        return sum;
    }

Java8でのコード

ストリームAPIとラムダ式を使って記述しました。

    public static int sum() {
        return IntStream.range(1, 1000).parallel().filter(x -> x % 3 ==0 || x % 5 == 0).sum();
    }

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?