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.
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? 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.
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).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With