find prime numbers between 1 to 100
16 views (last 30 days)
Show older comments
Answers (2)
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).'
1 Comment
Walter Roberson
on 17 Aug 2021
By the way, above result is not guaranteed. And even for what it does it could be improved.
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
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?
See Also
Categories
Find more on Discrete Math in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!