fork download
  1. object Main {
  2. def merge[A <% Ordered[A]](a: Stream[A], b: Stream[A]): Stream[A] =
  3. // ** Both `a` and `b` assume to be strictly increasing. **
  4. (a.headOption, b.headOption) match {
  5. case (Some(x), Some(y)) if x < y => x #:: merge(a.tail, b)
  6. case (Some(x), Some(y)) if x > y => y #:: merge(a, b.tail)
  7. case (Some(x), Some(_)) => x #:: merge(a.tail, b.tail)
  8. case (_, None) => a
  9. case _ => b
  10. }
  11.  
  12. def joinL[A <% Ordered[A]](xs: Stream[Stream[A]]): Stream[A] =
  13. xs.head.head #:: merge(xs.head.tail, joinL(xs.tail))
  14.  
  15. def minus[A <% Ordered[A]](a: Stream[A], b: Stream[A]): Stream[A] =
  16. // ** Both `a` and `b` assume to be strictly increasing. **
  17. (a.headOption, b.headOption) match {
  18. case (Some(x), Some(y)) if x < y => x #:: minus(a.tail, b)
  19. case (Some(x), Some(y)) if x > y => minus(a, b.tail)
  20. case (Some(_), Some(_)) => minus(a.tail, b.tail)
  21. case _ => a
  22. }
  23.  
  24. val primes: Stream[BigInt] = 2 #:: minus(Stream.iterate(3:BigInt)(_+1),
  25. joinL(primes.map{p => Stream.iterate(p*p)(_+p)}))
  26.  
  27. def main(args: Array[String]): Unit = {
  28. printExecutionTime { println(primes.take(100).mkString(", ")) }
  29. // => 2, 3, 5, 7, … , 541
  30. // => 18msec
  31.  
  32. printExecutionTime { println(primes(9999)) }
  33. // => 104729
  34. // => 150msec
  35. }
  36.  
  37. private def printExecutionTime(proc: => Unit) = {
  38. val start = System.currentTimeMillis
  39. proc
  40. println((System.currentTimeMillis - start) + "msec")
  41. }
  42. }
Success #stdin #stdout 0.86s 322624KB
stdin
sieve of Eratosthenes in Scala
stdout
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541
192msec
104729
480msec