Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I efficiently generate a list of primes in Perl 6?

Tags:

primes

raku

Generating a list of primes is incredibly easy in Perl 6 using is-prime:

my @primes = (^∞).grep: *.is-prime;

This works well enough if you need a relatively small number of primes, but is very inefficient for large numbers, since every number is independently checked.

Is there a way to access Perl 6's built-in prime checking logic to efficiently create a list of primes? Otherwise I'll need to build a sieve myself. Easy enough, but I'm afraid a sieve in high-level Perl 6 code will be almost as inefficient as the code I started with.

like image 343
mscha Avatar asked Apr 29 '17 23:04

mscha


People also ask

How do I get prime numbers in Perl?

Perl program to find prime numbers Write a program to check whether a number is prime or not. Step 2: Read the number to n. Step 3: Initialize d (flag) to 0. Step 4: if n is equal to 2,print number is prime.

How do you find a list of prime numbers?

How do you find a list of prime numbers? The prime numbers from 1 to 100 are: 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. Why is 1 not a prime number? 1 is not a prime number because it has only one factor, namely 1.

How do you find the number of primes less than n?

The prime number theorem provides a way to approximate the number of primes less than or equal to a given number n. This value is called π(n), where π is the “prime counting function.” For example, π(10) = 4 since there are four primes less than or equal to 10 (2, 3, 5 and 7).


1 Answers

If you run your program with --profile, you will see that more than 99% of the time is spent in Int.is-prime. Since that effectively is just a wrapper around nqp::isprime_I(), I have tried to run similar code without the wrapper. But that doesn't change anything noticeably. So the brunt of the work is being done in nqp::isprime_I().

So the only option you really have is to parallelize your searches for primes. In the (nearer) future, hyper would be your friend here. But that is currently at the "initial naive implementation" phase, with a more robust implementation being discussed in: https://gist.github.com/jnthn/6a80a9712fb38b32537f9f0e46fca6d7

Until then, if you want to run things faster, you would have to manually break up the range of values you want to check for primedness and run them within a start block, and collect the results from the resulting Promise.

like image 85
Elizabeth Mattijsen Avatar answered Jan 07 '23 13:01

Elizabeth Mattijsen