Find the amount of prime numbers between two numbers by using only length and primes

6 views (last 30 days)
Is there any possible way to find the amount of prime numbers between two numbers by using only the commands length and primes? So far I have tried this, but whenever I change the number in the if statements to something larger than 2, the code suddenly won't work.
P = primes(20000);
p=[];
if P >= 10000
p = [p, P];
end
amount = length(p)

Accepted Answer

Cris LaPierre
Cris LaPierre on 20 Aug 2020
Edited: Cris LaPierre on 20 Aug 2020
Yes, it is. Consider what primes returns: Prime numbers less than or equal to input value.
If I can find out the number of primes less than or equal to two different values, then I can use a little math to figure out the number of primes between those two values.
  7 Comments
Cris LaPierre
Cris LaPierre on 20 Aug 2020
Edited: Cris LaPierre on 20 Aug 2020
Yes. If I know there are 3 prime numbers <=6, and 8 prime numbers <= 20, then I can figure out the number of primes between 6 and 20 by taking the difference: 8-3 = 5.
iseinas
iseinas on 20 Aug 2020
OMG it was really easy, I totally forgot about that,, thank you so much. My math skills really dropped right there :c You really helped a lot.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!