fork(2) download
  1. object Main extends App { // base code by stewSquared (see 3qb5m0) from
  2. // your code goes here // http://stackoverflow.com/q/20985539/849891,
  3. def primes(): Stream[Int] = { // with postponement added by Will Ness
  4. def merge(a: Stream[Int], b: Stream[Int]): Stream[Int] = {
  5. def next = a.head min b.head
  6. Stream.cons(next, merge(if (a.head == next) a.tail else a,
  7. if (b.head == next) b.tail else b))
  8. }
  9. def test(n: Int, q: Int,
  10. compositeStream: Stream[Int],
  11. primesStream: Stream[Int]): Stream[Int] = {
  12. if (n == q) test(n+2, primesStream.tail.head * primesStream.tail.head,
  13. merge(compositeStream,
  14. Stream.from(q, 2*primesStream.head).tail),
  15. primesStream.tail)
  16. else if (n == compositeStream.head) test(n+2, q, compositeStream.tail,
  17. primesStream)
  18. else Stream.cons(n, test(n+2, q, compositeStream, primesStream))
  19. }
  20. Stream.cons(2, Stream.cons(3, Stream.cons(5,
  21. test(7, 25, Stream.from(9, 6), primes().tail.tail))))
  22. }
  23. // 100: 0.37s-382M 1k: 0.40s-383M 2k:0.43s-382M (zero time=0.37)
  24. print(primes().drop(10000).head)
  25. // 10k: 0.8s-382M n^1.22 25k: 2.06s-382M n^1.49
  26. } // 50k:5.53s-382M n^1.61 80k:11.04s-383M n^1.55
Success #stdin #stdout 0.77s 382080KB
stdin
Standard input is empty
stdout
104743