Write a function used to list primes

조회 수: 8 (최근 30일)
Ruihan Yi
Ruihan Yi 2020년 5월 16일
댓글: Ruihan Yi 2020년 5월 20일
I'm a beginner in MATLAB.
This task is to wirte a function called 'primeList' to list all primes form 1 to p. isprime is not allowed to be used.
AND the background of this queation is Eratosthenes Sieve so I must use this sieve (mod is not allowed)
I have tried for more than 3 days, now, what I writed can print the primes when p>4.
However, I don't know how to let it print when p =2 or 3?
my code ↓
function primeList=EratosthenesSieve(p) % creat a list of prime numbers from 2 to p
%p=input('please enter a positive integer p, p>2, p= ')
%take a positive integer p as input (not essential)
primeList=1:p;
a=2; %The first prime is 2
while a.^2<=p %End when reach sqrt(p)
primeList(a^2:a:p)=0 %Make all the numbers which are multiples of a to be 0
primeList(1)=0; %Make 1 to be 0 as 1 is neither prime nor composite
a=find(primeList>a,1); %find the next unmarked number to continue
end
primeList(primeList==0)=[] %only keep primes as an array
%special conditions:p=2 or 3 ???
end
  댓글 수: 1
Ruihan Yi
Ruihan Yi 2020년 5월 16일
I'm actually not a native English speaker, so if my expression is confusing you, thank you for pointing it out for me.

댓글을 달려면 로그인하십시오.

답변 (1개)

Devineni Aslesha
Devineni Aslesha 2020년 5월 18일
Hi Ruihan
Shift the line 'primeList(1)=0;' from the while loop to above the while loop to print the correct prime numbers when p = 2 or 3.
  댓글 수: 1
Ruihan Yi
Ruihan Yi 2020년 5월 20일
You are right! Thank you very much!!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by