How to print all prime numbers between 1 and 100 using a for loop?

121 vues (au cours des 30 derniers jours)
Elijah McNeil
Elijah McNeil le 28 Oct 2020
Commenté : Voss le 29 Fév 2024
for f = (1:100)
f
isprime(f)
j = all(f)
end
fprintf('%j',j)
This is what I have, I either get j as logical or if I change it to "fprintf('%f', f)" I get f = 100.
I need to print the prime numbers.
What am I doing wrong?
  2 commentaires
Maheen
Maheen le 29 Fév 2024
Déplacé(e) : Voss le 29 Fév 2024
prime number between 7 and 47
Voss
Voss le 29 Fév 2024
@Maheen: The accepted answer finds primes between 1 and 100. Try to adapt it to find primes between 7 and 47.

Connectez-vous pour commenter.

Réponse acceptée

KSSV
KSSV le 28 Oct 2020
Modifié(e) : KSSV le 28 Oct 2020
num = 1:100 ; % numbers till 100
idx = isprime(num) ; % get logical indices of prime numebrs
num(idx) % print the prime numbers
ans = 1×25
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
  7 commentaires
Stephen23
Stephen23 le 28 Oct 2020
The square brackets here are completely superfluous:
primenum = [num(idx)]
Get rid of them, they do absolutely nothing.
KSSV
KSSV le 28 Oct 2020
Yes @Stephen..
primenum = num(idx) ;
is enough.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by