A10.m - Finding first N primes (using a while loop with an if statement)

% get info from user
N = input('How many prime numbers do you want to find?  ');

n = 1;          % n will step through every integer until N primes are found
nPrimes = 0;    % nPrimes will count the number of prime numbers found

while nPrimes < N       % while loop goes until nPrimes = N, then it stops
    if isprime(n)
        fprintf('%i\n',n)           % display prime numbers to command
                                    % window as they are found
        nPrimes = nPrimes + 1;      % increment the number of primes found
    end

    n = n + 1;          % increment the number counter
end

Download A10.m

A simple example of using a while loop combined with an if statement.


Monkey Home   |    Prev   |   Next