Skip to content

Instantly share code, notes, and snippets.

@piotrga
Created December 25, 2011 22:06
Show Gist options
  • Save piotrga/1519814 to your computer and use it in GitHub Desktop.
Save piotrga/1519814 to your computer and use it in GitHub Desktop.
Lazy prime numbers
def primes : Stream[Int] = {
def findNextPrime(primes: List[Int])={
var i = primes.head+1
while(primes.exists(x => i % x == 0)){i+=1}
i
}
def prim(primes:List[Int]): Stream[Int] = primes match{
case Nil => 1 #:: 2 #:: prim(List(2))
case _ => {
val next = findNextPrime(primes)
next #:: prim(next::primes)
}
}
prim(Nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment