Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@mishokaz

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

参考: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番目の素数
  }
}

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
2
Help us understand the problem. What are the problem?