Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Created October 31, 2012 18:49
Show Gist options
  • Save martintrojer/3989043 to your computer and use it in GitHub Desktop.
Save martintrojer/3989043 to your computer and use it in GitHub Desktop.
sieve of eratosthenes + newton (lazy)
def sqrtStream(x: Double): Stream[Double] = {
def improve(guess: Double) = (guess + x / guess) / 2
lazy val guesses: Stream[Double] = 1 #:: (guesses map improve)
guesses
}
sqrtStream(4).take(10).toList
def sieve(s: Stream[Int]): Stream[Int] =
s.head #:: sieve(s.tail filter (_ % s.head != 0))
def from(n: Int): Stream[Int] = n #:: from(n + 1)
val primes = sieve(from(2))
primes.take(10).toList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment