Prime numbers from 2 till hundred?
Afficher commentaires plus anciens
How to use control flow statements that returns all the prime numbers from 2 till hundred?
6 commentaires
KSSV
le 10 Nov 2021
iwant = primes(100)
Jan
le 10 Nov 2021
What exactly are "control flow statements"?
Walter Roberson
le 10 Nov 2021
Modifié(e) : Walter Roberson
le 10 Nov 2021
"for" and "if" and "elseif" and "while" and "break" and "continue" are control-flow statements, along with "switch" and "case"
Jan
le 10 Nov 2021
@Walter Roberson: Thanks.
@Ahmad Omar: This sounds like a homework question. As usual: Please post, what you have tried so far and ask a specific question.
Steven Lord
le 10 Nov 2021
I'd classify most if not all of the functions in the Loops and Conditional Statements category in the documentation as control-flow statements. [return, parfor, and otherwise are the main additions to Walter's list. I mainly wanted to point out the existence of the category documentation pages.]
Jan
le 11 Nov 2021
Is the question meaningful? Is it possible to calculate prime numbers with control flow statements only, or without control flow statements? Maybe a flow chart is meant?
Réponses (1)
Rushil
le 29 Jan 2025
Hi Ahmad
I believe that this task can be accomplished using a sieve of eratosthenes using control flow statements like for/if/continue etc. The sieve works in O(n log logn) time, which is usually fast enough for small values of “n” (in this case n=100). Below is the implementation of the algorithm, it stores all the prime numbers in the array “prime”:
n = 100; % range of numbers is [2,n]
prime = [];
is_pr = ones(1,n);
for i=2:n
if ~is_pr(i)
continue
end
prime = [prime i];
for j=2*i:i:n
is_pr(j) = 0;
end
end
prime
Since the task is concerned with using control flow statements, the above code finds all the primes in [2,n]. However, a more optimised approach may be to use the MATLAB function “primes”. You can read more about it here:
Hope it helped.
larush
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!