Skip to content

Instantly share code, notes, and snippets.

@Swind
Created February 14, 2012 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Swind/1824813 to your computer and use it in GitHub Desktop.
Save Swind/1824813 to your computer and use it in GitHub Desktop.
[Scala][Algorithm] 用Scala找質數的範例
object FindPrimse {
def main(args: Array[String]) {
val result = fillPrimeList(10000)
result foreach println
}
def fillPrimeList(max: Int, list: List[Int] = List(3, 2)): List[Int] = {
if (list.head < max)
fillPrimeList(max, findNextPrime(list, list.head + 2) :: list)
else
list
}
def findNextPrime(primeList: List[Int], nextNumber: Int): Int = {
val upperBound = math.sqrt(nextNumber)
if (primeList.filter(_ <= upperBound) exists (nextNumber % _ == 0))
findNextPrime(primeList, nextNumber + 2)
else
nextNumber
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment