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 件のコメント
James Tursa
2019 年 2 月 7 日
What would be your exact desired output for the example you have shown?
Preethi
2019 年 2 月 8 日
Are you providing a set of numbers as input and you want to display prime numbers?
Sarah Crimi
2019 年 2 月 8 日
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!