Created
February 14, 2012 08:30
-
-
Save Swind/1824813 to your computer and use it in GitHub Desktop.
[Scala][Algorithm] 用Scala找質數的範例
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
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