Skip to content

Instantly share code, notes, and snippets.

@ChrisCoffey
Last active August 29, 2015 14:14
Show Gist options
  • Save ChrisCoffey/8d66b53ad59d6d6c0e32 to your computer and use it in GitHub Desktop.
Save ChrisCoffey/8d66b53ad59d6d6c0e32 to your computer and use it in GitHub Desktop.
A Functional Prime Number Generator In Scala
def primes: Stream[Long] = 2 #:: prime3
// performance: avoid redundant divide by two, so this starts at 3
private val prime3: Stream[Long] = {
def next(i: Long): Stream[Long] =
if (prime(i))
i #:: next(i + 2)
else
next(i + 2) // tail
3 #:: next(5)
}
private def prime(i: Long) =
prime3 takeWhile (math.sqrt(i).>= _) forall { i % _ != 0 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment