Reputation: 6246
I was trying to calculate the first x
prime numbers by using the following line of code:
(1 to Int.MaxValue).filter(is_prime _).take(x)
However, the program just didn't stop and I had to close it (I didn't want to wait until Int.MaxValue was reached). How could I rewrite this to work in normal time while mantaining the simplicity?
Upvotes: 1
Views: 727
Reputation: 42607
You can also use a Stream (or Iterator - see the comments below)
Stream.from(1).filter(is_prime).take(x)
Upvotes: 5
Reputation: 13959
Range
will traverse the whole collection with filter. Try using a view
instead:
(1 to Int.MaxValue).view.filter(is_prime _).take(x)
Upvotes: 3