Skip to content

Instantly share code, notes, and snippets.

@t3hnar
Created November 2, 2012 17:20
Show Gist options
  • Save t3hnar/4002895 to your computer and use it in GitHub Desktop.
Save t3hnar/4002895 to your computer and use it in GitHub Desktop.
Primes
/**
* @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