Last active
May 31, 2016 06:43
-
-
Save omiend/88512c05f3ea56db9fcc to your computer and use it in GitHub Desktop.
Scalaで素数を出力する(Scala De Sieve of Eratosthenes)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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