Skip to content

Instantly share code, notes, and snippets.

@omiend
Last active May 31, 2016 06:43
Show Gist options
  • Save omiend/88512c05f3ea56db9fcc to your computer and use it in GitHub Desktop.
Save omiend/88512c05f3ea56db9fcc to your computer and use it in GitHub Desktop.
Scalaで素数を出力する(Scala De Sieve of Eratosthenes)
import scala.collection.immutable.List
import scala.annotation.tailrec
/** 素数を取得 */
object PrimeNumber {
def main(args: Array[String]): Unit = {
// 1は除外(素数についてのお約束ごと)
searchPrimeNumber(List.range(2, 10000))
}
/** 素数を出力する */
// @tailrecをつけると末尾再帰出ない場合コンパイルエラーが発生する(コンパイルエラーを発生してくれる)
// 末尾再帰にしておくと、Scalaコンパイラが最適かをしてくれる
@tailrec
def searchPrimeNumber(numberList: List[Int]): Unit = {
// Headが存在する場合のみ処理
numberList match {
case x :: xs => {
// コンソール出力
println(x)
// 現在の値で割り切れる後続の値を除外する(エラトステネスのふるい)
searchPrimeNumber(xs.filter(_ % x != 0))
}
case _ => //終了
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment