3
2

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.

え!! 9行で素数を!?

Posted at

出来らあっ!

val primeSequence = sequence {
    val primes = mutableListOf<Int>()
    (2..Int.MAX_VALUE).forEach { int ->
        if (primes.all { int % it != 0 }) {
            primes += int
            yield(int)
        }
    }
}

使ってみる

先頭の10要素を標準出力する

fun main() {
    primeSequence
        .take(10)
        .forEach(::println)
}
結果の標準出力 ``` 2 3 5 7 11 13 17 19 23 29 ```

第10000要素を標準出力する

fun main() {
    primeSequence
        .elementAt(10000 - 1)
        .let(::println)
}

結果の標準出力

104729

これくらいなら一瞬。
もう1桁増やすと少し待たされる。

解説

知らない人がいそうなのは次の2つくらいか。

ロジックは解説するほどではないだろう。

改善の余地

  • primeSequence を使うたびに素数のリストを最初から計算し直してしまうのが無駄
  • 並列処理で高速化できそう
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?