How can I display prime numbers with their number of order?

1 回表示 (過去 30 日間)
Tayfun Aydogmus
Tayfun Aydogmus 2021 年 5 月 7 日
コメント済み: Tayfun Aydogmus 2021 年 5 月 10 日
Hello everyone,
I'm quite new to Matlab and was working on a code to display prime numbers between 2 and an user defined input. Now I wanna make "a little" change by showing the user not only all the prime numbers between 2 and the users input but also the number of order for each prime number like this for example.
User Input = 10
Output:
  1. 2
  2. 3
  3. 5
  4. 7
My question would be how can I do this with my current code
limit = input('Prime numbers up to : ');
if limit == 1
disp('Please enter a number greater than 2!')
end
for n = 2:limit
identDivisor = logical(false);
k = 2;
while k < floor(sqrt(n))+1 && identDivisor == false
if mod(n,k) == 0
identDivisor = true;
end
k = k + 1;
end
if identDivisor == false
disp(n)
end
end
return

採用された回答

David Fletcher
David Fletcher 2021 年 5 月 7 日
A simple solution would be to just add a counter variable:
limit = input('Prime numbers up to : ');
if limit == 1
disp('Please enter a number greater than 2!')
end
order=1;
for n = 2:limit
identDivisor = logical(false);
k = 2;
while k < floor(sqrt(n))+1 && identDivisor == false
if mod(n,k) == 0
identDivisor = true;
end
k = k + 1;
end
if identDivisor == false
fprintf('%d. %d\n',order,n)
order=order+1;
end
end
return

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by