Array of N prime numbers
조회 수: 9 (최근 30일)
이전 댓글 표시
Hello. I'm new to MatLab. I've just written a code to identify if a given number N is a prime number.
Basically, that's it:
function [out] = myIsPrime(n)
if n == 1
out = 0;
elseif n == 2
out = 1;
elseif all(rem(n,2:n-1) ~= 0)
out = 1;
else
out = 0;
end
end
Now I want my output to be the first 'N' prime numbers counting from 2 and up.
I've been trying for hours but my brain is just frozen. How do I do that using if, for or while loops?
댓글 수: 1
Gangga Fardede
2017년 10월 30일
I want to ask, how to make a row, if we input number, the output will display prime number have a lot of n Like we input '4' abd will dispay '2 3 5 7'
채택된 답변
Walter Roberson
2016년 6월 26일
while the count of primes found is less than your target count, keep trying the next number in sequence to determine whether it is prime; if it is then increment the count of primes found and store the prime in your array.
댓글 수: 3
Walter Roberson
2016년 6월 26일
num_primes_found = num_primes_found + 1;
list_of_primes(num_primes_found) = the_candidate_number;
To store only N numbers, use a while loop on num_primes_found
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!