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

조회 수: 122 (최근 30일)
Elijah McNeil
Elijah McNeil 2020년 10월 28일
댓글: Voss 2024년 2월 29일
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
Maheen
Maheen 2024년 2월 29일
이동: Voss 2024년 2월 29일
prime number between 7 and 47
Voss
Voss 2024년 2월 29일
@Maheen: The accepted answer finds primes between 1 and 100. Try to adapt it to find primes between 7 and 47.

댓글을 달려면 로그인하십시오.

채택된 답변

KSSV
KSSV 2020년 10월 28일
편집: KSSV 2020년 10월 28일
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
Stephen23
Stephen23 2020년 10월 28일
The square brackets here are completely superfluous:
primenum = [num(idx)]
Get rid of them, they do absolutely nothing.
KSSV
KSSV 2020년 10월 28일
Yes @Stephen..
primenum = num(idx) ;
is enough.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by