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

조회 수: 16 (최근 30일)
Devon Von Lichtenstein
Devon Von Lichtenstein 2018년 4월 26일
댓글: Rik 2020년 12월 7일
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에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by