Using a While Loop to find Prime Values

How can I crate a program that display rather tha verifies umbers that are prime? I tried
x=23;
y=2;
while rem(x,y)~=0
y=y+1;
end
if y==x
disp('Prime');
else
disp('Not Prime');
end
but it this only shows prime and not prime. I am trying to use a while loop. Serious answers please.

3 个评论

What would be your exact desired output for the example you have shown?
Are you providing a set of numbers as input and you want to display prime numbers?
This is code to find the first 20 prime numbers.
%Create a list of first 200 numbers.
x = 1:200;
x = x';
%Preallocate for primes vector.
primes=zeros(200,1)
%Preset the counter to 2 and prime_numbers to 0.
counter = 2;
prime_nums = 0;
while(prime_nums<20)
%
%x(counter) is the number that will be tested.
num = x(counter)
flag = 0;
for i = 2:(num-1)
a = mod(num,i) ;
if a==0
flag = flag + 1; %Update flag when item is divisable by a number prior to it that is not 2 or greater.
end
end
%If the item is divisable by a number prior to it that is 2 or greater, it is not a prime.
if(flag>0)
primes(counter-1,1)=0;
else
%If the item is not divisable by a number prior to it that is 2 or greater, it is a prime.
prime_nums = prime_nums +1;
primes(counter-1,1) = num;
end
%Update counter to move to next item in list.
counter = counter+1
end
%Get the nonzeros from primes vector to get the first 20 primes.
result=nonzeros(primes);
%Display results.
disp(result)

请先登录,再进行评论。

回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by