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

45 Ansichten (letzte 30 Tage)
Devon Von Lichtenstein
Devon Von Lichtenstein am 26 Apr. 2018
Kommentiert: Rik am 7 Dez. 2020
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 Kommentare
nassnnf
nassnnf am 7 Dez. 2020
can you help me to solve similiar question.the questions is list 50 prime number after 230 in 10x5 matrik
Rik
Rik am 7 Dez. 2020
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?

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Rik
Rik am 26 Apr. 2018
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 Kommentar
Rik
Rik am 30 Apr. 2018
Did my answer solve your problem? If so, please mark it as accepted answer, if not, feel free to comment with your remaining questions.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by