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

11 vues (au cours des 30 derniers jours)
Devon Von Lichtenstein
Devon Von Lichtenstein le 26 Avr 2018
Commenté : Rik le 7 Déc 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 commentaires
nassnnf
nassnnf le 7 Déc 2020
can you help me to solve similiar question.the questions is list 50 prime number after 230 in 10x5 matrik
Rik
Rik le 7 Déc 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?

Connectez-vous pour commenter.

Réponses (1)

Rik
Rik le 26 Avr 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 commentaire
Rik
Rik le 30 Avr 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by