Help writing a for/while loop to identify and sort prime numbers

22 次查看(过去 30 天)
I have a class assignment that requires using a for or while loop to identify prime numbers between 10-500. After the numbers have been identified as prime, they need to be classified as "twin" if there is another prime within 2, or "isolated" if there is not another prime within 2. The built-in function "isprime" is not allowed.
I have hit a wall and don't even know where to go from here. So far, I have been able to identify prime numbers, but am stuck on the sorting process.
n = 500; %maximum prime number to find
primes = 2;
for i = 1:n %code I found to help identify primes
if mod(i+2,primes) ~= 0
primes = [primes, i+2];
end
  3 个评论
nassnnf
nassnnf 2020-12-7
can you help me to solve similiar question.the questions is list 50 prime number after 230 in 10x5 matrik
Rik
Rik 2020-12-7
It is your homework. What have you tried? Also, this question has two parts: finding 50 prime numbers and storing them in a 10x5 matrix. Which of these two is causing you trouble?

请先登录,再进行评论。

回答(1 个)

Rik
Rik 2018-4-26
You already have a list of all the primes, so you don't need isprime anymore. What you now want to do is figure out the distance between every prime and it's two neighbor primes. You can do this several ways. Because this is a homework question, I will not give a complete working solution.
n = 500; %maximum prime number to find
primes = 2;
for i = 1:n %code I found to help identify primes
if mod(i+2,primes) ~= 0
primes = [primes, i+2];
end
end
inter_prime_distance=diff(primes);
Now you have the distance between each prime pair, you can compare that to 2. You should note that inter_prime_distance is 1 shorter than primes.
If you have more question or need clarification, don't hesitate to comment below.
  1 个评论
Rik
Rik 2018-4-30
Did my answer solve your problem? If so, please mark it as accepted answer, if not, feel free to comment with your remaining questions.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Downloads 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by