find prime numbers between 1 to 100

16 views (last 30 days)
Sameer Khan
Sameer Khan on 23 Mar 2021
Commented: Walter Roberson on 17 Aug 2021
write a program using nested For loop to determine prime numbers from 1 to 100 in matlab

Answers (2)

Walter Roberson
Walter Roberson on 15 Aug 2021
N = 100;
is_a_prime(1:N) = true;
for k = 3 : N
for c = 1 : 100
if mod(k, randi([2 k-1])) == 0
is_a_prime(k) = false;
break;
end
end
end
find(is_a_prime).'
ans = 29×1
1 2 3 5 7 11 13 17 19 23
  1 Comment
Walter Roberson
Walter Roberson on 17 Aug 2021
By the way, above result is not guaranteed. And even for what it does it could be improved.

Sign in to comment.


Jan
Jan on 24 Mar 2021
Edited: Jan on 17 Aug 2021
You got a valuable hint already, that nested loops are useful:
for k = 1:100
for f = 2:100
% Now check if f is a divider of k
end
% If no divider was found, k is a prime
end
Does the innerloop need to run until 100?
  1 Comment
DGM
DGM on 24 Mar 2021
I'll add, does k need to include all numbers from 1:100? Is there an obvious pattern of numbers k can skip?

Sign in to comment.

Categories

Find more on Discrete Math in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!