How to code how many prime numbers are there between 1 million and 2 million on MATLAB

1.3k Views Asked by At

How would I find the total number of prime numbers between 1 million and 2 million on MATLAB. I have the code for displaying every prime number between 2 integers being:

n = firstnumber : secondnumber;
p = isprime(n);
n(p)     %displays the primes

But how would I code it so it gives me a total number of primes between 2 numbers.

Any help will be appreciated.

2

There are 2 best solutions below

0
On

Not necessarily the most efficient way of doing it but for your numbers it's still very fast:

p = primes(secondnumber);
n = length(find(p>=firstnumber));

About 20ms here.

0
On

With Mathematica

Select[Range[10^6, 2*10^6], PrimeQ] // Length // Timing
{0.515625, 70435}

I suspect an equally fast test existing in matlab, using the function isprime() mapped into an array.