Here is code that returns the first
N prime numbers:
function [primes] = findFirstNPrimes(N) % Accepts an integer, N. % Returns the first N primes. primes(1) = 2; % first prime i = 3; % numbers from i and on to be tested while length(primes) <= N % 1 x N array of i's, N - current size of: primes test = i * ones(1, length(primes)); % element-by-element modulo division remainder = test - primes .* floor(test ./ primes); % if there is a 0 in r, i is not prime. isNotPrime = any((remainder == 0)); % if i is prime, append it to the array of primes if (!isNotPrime) primes(end + 1) = i; endif % increment, to check next number i += 1; endwhile endfunction
p = findFirstNPrimes(20)
Columns 1 through 17:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59
Columns 18 through 21:
61 67 71 73
I would like some recommendation and review regarding:
Octave coding style and conventions. (These are my first steps in Octave.)
Complexity and performance of the code, having in mind most operations performed on arrays.
Readability & any possible improvements.