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

Scalaでエラトステネスのふるい

Posted at

参考:wikipedia:エラトステネスの篩

import scala.collection.mutable

object Main{
  def main(args: Array[String]): Unit = {
    val N = 120 // N以下の素数
    val primes = mutable.BitSet()

    primes(2) = true

    // すべての数を素数として初期化。2以外の偶数は素数にはなりえないので除外。
    for (i <- 3 to N by 2) {
      primes(i) = true
    }

    // ふるいにかける。
    for (i <- 3 to Math.sqrt(N).toInt by 2 if primes(i); j <- i * 2 to N by i) {
      primes(j) = false
    }

    println(primes.mkString(","))
    println(primes.drop(9).head) // 10番目の素数
  }
}

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