object Main
extends App
{ // base code by stewSquared (see 3qb5m0) from // your code goes here // http://stackoverflow.com/q/20985539/849891,
def primes
(): Stream
[Int
] = { // with postponement added by Will Ness def merge
(a
: Stream
[Int
], b
: Stream
[Int
]): Stream
[Int
] = { def next
= a.
head min b.
head Stream.
cons(next, merge
(if (a.
head == next
) a.
tail else a,
if (b.
head == next
) b.
tail else b
)) }
compositeStream: Stream[Int],
primesStream: Stream[Int]): Stream[Int] = {
if (n
== q
) test
(n+
2, primesStream.
tail.
head * primesStream.
tail.
head,
merge(compositeStream,
Stream.from(q, 2*primesStream.head).tail),
primesStream.tail)
else if (n
== compositeStream.
head) test
(n+
2, q, compositeStream.
tail,
primesStream)
else Stream.
cons(n, test
(n+
2, q, compositeStream, primesStream
)) }
Stream.cons(2, Stream.cons(3, Stream.cons(5,
test(7, 25, Stream.from(9, 6), primes().tail.tail))))
}
// 100: 0.37s-382M 1k: 0.40s-383M 2k:0.43s-382M (zero time=0.37)
print(primes().drop(10000).head)
// 10k: 0.8s-382M n^1.22 25k: 2.06s-382M n^1.49
} // 50k:5.53s-382M n^1.61 80k:11.04s-383M n^1.55
b2JqZWN0IE1haW4gZXh0ZW5kcyBBcHAgeyAgLy8gYmFzZSBjb2RlIGJ5IHN0ZXdTcXVhcmVkIChzZWUgM3FiNW0wKSBmcm9tIAoJLy8geW91ciBjb2RlIGdvZXMgaGVyZSAgIC8vICBodHRwOi8vc3RhY2tvdmVyZmxvdy5jb20vcS8yMDk4NTUzOS84NDk4OTEsCglkZWYgcHJpbWVzKCk6IFN0cmVhbVtJbnRdID0geyAgLy8gd2l0aCBwb3N0cG9uZW1lbnQgYWRkZWQgYnkgV2lsbCBOZXNzCiAgICAgIGRlZiBtZXJnZShhOiBTdHJlYW1bSW50XSwgYjogU3RyZWFtW0ludF0pOiBTdHJlYW1bSW50XSA9IHsKICAgICAgICBkZWYgbmV4dCA9IGEuaGVhZCBtaW4gYi5oZWFkCiAgICAgICAgU3RyZWFtLmNvbnMobmV4dCwgbWVyZ2UoaWYgKGEuaGVhZCA9PSBuZXh0KSBhLnRhaWwgZWxzZSBhLAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChiLmhlYWQgPT0gbmV4dCkgYi50YWlsIGVsc2UgYikpCiAgICAgIH0KICAgICAgZGVmIHRlc3QobjogSW50LCBxOiBJbnQsIAogICAgICAgICAgICAgICAgICAgICAgIGNvbXBvc2l0ZVN0cmVhbTogU3RyZWFtW0ludF0sIAogICAgICAgICAgICAgICAgICAgICAgIHByaW1lc1N0cmVhbTogU3RyZWFtW0ludF0pOiBTdHJlYW1bSW50XSA9IHsKICAgICAgICBpZiAobiA9PSBxKSB0ZXN0KG4rMiwgcHJpbWVzU3RyZWFtLnRhaWwuaGVhZCAqIHByaW1lc1N0cmVhbS50YWlsLmhlYWQsCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIG1lcmdlKGNvbXBvc2l0ZVN0cmVhbSwgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFN0cmVhbS5mcm9tKHEsIDIqcHJpbWVzU3RyZWFtLmhlYWQpLnRhaWwpLAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICBwcmltZXNTdHJlYW0udGFpbCkKICAgICAgICBlbHNlIGlmIChuID09IGNvbXBvc2l0ZVN0cmVhbS5oZWFkKSB0ZXN0KG4rMiwgcSwgY29tcG9zaXRlU3RyZWFtLnRhaWwsCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHByaW1lc1N0cmVhbSkKICAgICAgICBlbHNlIFN0cmVhbS5jb25zKG4sIHRlc3QobisyLCBxLCBjb21wb3NpdGVTdHJlYW0sIHByaW1lc1N0cmVhbSkpCiAgICAgIH0KICAgICAgU3RyZWFtLmNvbnMoMiwgU3RyZWFtLmNvbnMoMywgU3RyZWFtLmNvbnMoNSwgIAogICAgICAgICB0ZXN0KDcsIDI1LCBTdHJlYW0uZnJvbSg5LCA2KS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