home

Scientific Computing (Psychology 9040a)

Fall, 2021

Prime Number Test: sample solution


Here is one way of doing this:

N = input('Enter a number: ');

number_is_prime = true;
for i = 2:(N-1)
    if (mod(N,i)==0)
        number_is_prime = false;
    end
end

if (number_is_prime == true)
    fprintf('The number %d is prime\n', N);
else
    fprintf('The number %d is not prime\n', N);
end

As a further exercise, think about how you could modify the code above so that it is more efficient. Here are two hints: