Created
November 2, 2012 17:20
-
-
Save t3hnar/4002895 to your computer and use it in GitHub Desktop.
Primes
This file contains hidden or 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
/** | |
* @author Yaroslav Klymko | |
*/ | |
object Primes { | |
val naturals = { | |
def loop(n: Long): Stream[Long] = n #:: loop(n + 1) | |
loop(1) | |
} | |
val primes: Stream[Long] = { | |
def loop(naturals: Stream[Long]): Stream[Long] = | |
naturals.head #:: loop(naturals.tail.dropWhile(!isPrime(_))) | |
loop(naturals.tail) | |
} | |
def isPrime(n: Long) = { | |
val sqrt = math.sqrt(n) | |
primes.collectFirst { | |
case p if p > sqrt => true | |
case p if n % p == 0 => false | |
}.get | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment