In: Computer Science
In MATLAB define a function named primes that takes a non-negative integer, ?, as its only argument and returns a row vector containing the first ? prime numbers in order. Assume that the first prime number is 2. Other than the zeros function, the ones function, and the colon (:) operator, you may not use any Matlab built-in array functions.
function [primes] = findFirstNPrimes(N)
%returns the array with first n primes
%first prime
primes(1) = 2;
i = 3;
while length(primes) <= N
%taking remainder with all the primes so far
remainder = mod(i,primes);
% if all inNotPrime is 0 the number is a prime since remainder is
% not zero for all the numbers in prime
isNotPrime = sum((remainder == 0));
%adding prime number to the array
if (isNotPrime==0)
primes(end + 1) = i;
end
%checking for next the number
i =i+ 1;
end
end