Clear Filters
Clear Filters

Array of N prime numbers

9 views (last 30 days)
Leandro  Cavalheiro
Leandro Cavalheiro on 26 Jun 2016
Commented: Gangga Fardede on 30 Oct 2017
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 Comment
Gangga Fardede
Gangga Fardede on 30 Oct 2017
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'

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 26 Jun 2016
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 Comments
Walter Roberson
Walter Roberson on 26 Jun 2016
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
Leandro  Cavalheiro
Leandro Cavalheiro on 26 Jun 2016
Edited: Walter Roberson on 26 Jun 2016
I made it!
function [primes] = myNPrimes(N)
primes = 0;
k = 0;
f = 0;
while size(primes,2) < N
k = k + 1;
if k == 1
out = 0;
elseif k == 2
out = 1;
elseif all(rem(k,2:k-1) ~= 0)
out = 1;
else
out = 0;
end
if out == 1
f = f+1;
primes(f) = k;
end
end
end
Thanks

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!