% Unit 2 (MATLAB Course @ UAM)
% (c) Alexander Knebe

%======================================
% check for prime number
%======================================
clear all
clc

% type the integer number you want to know if it is a prime number or not
n=input('please give an integer number = ');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SOLUTION #1 (using a while-loop)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% we start with testing if n can be divided by div=2
div=n-1;

% we try to divide n by div=n-1, n-2, n-3, ..., 2
while (rem(n,div) ~= 0)   
    % in the next step test for division by div+1
    div = div - 1;
end

if (div == 1)
    disp('n is a prime number')
else
    disp('n is not a prime number')
    disp('and the largest number it can be divided by is')
    div
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SOLUTION #2 (more elegant solution!)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
div = [2:n-1];
p   = mod(n,div);
i   = find(p==0);
if (length(i)==0)
       disp('n is a prime number') 
else
    disp('n is not a prime number')
    disp('it can be divided by:')
    div(i)
end

