Lars Malmsteen
Lars Malmsteen

Reputation: 768

Getting the first 10-digit prime number using lazy lists in Raku

I'm trying to get the first 10-digit prime number using the lazy lists. Here is my take based on the (already given) code for computing the prime numbers:

my @primes = 2,3,5, {first * %% none(@_), (@_[*-1] ... Inf)} ...  -> $s {$s.chars == 10};

say @primes[@primes.elems-1];

The problem with that code is that it takes too long to finish.

Is there any quick method to get that first 10-digit prime number?

Upvotes: 8

Views: 181

Answers (1)

Jonathan Worthington
Jonathan Worthington

Reputation: 29454

You can make it faster by:

  • Starting from the smallest 10 digit number (no point going through a bunch of candidates that would never match even if they are prime)
  • Using the fast built-in is-prime method rather than a hand-rolled algorithm

Thus getting:

say (1_000_000_000..*).first(*.is-prime)

Which produces:

1000000007

You could filter out evens too, but I suspect is-prime rejects those as fast as you'd separately test them anyway. (Also, it turns out the number is so close to the first 10-digit number that nothing aside from stating at 1_000_000_000 matters in practice.)

Upvotes: 12

Related Questions