% Jake Bobowski
% August 22, 2017
% Created using MATLAB R2014a

% A function that can be called to find all the prime numbers between the
% positive integers a and b, where b > a.


function f = primes(a, b) % Start the function.
    if rem(a, 1) == 0 && rem(b, 1) == 0 && a > 0 && b > 0 && b > a % Check that a and b are positive integers with b > a.
        x = 0; % Counter variable used to index the vector of prime numbers
        for i = a:b
            cnt = 0; % Counter variable used to stop the while loop.
            if (i ~= 1 && mod(i, 2) == 1 && mod(sum(int2str(i)-48), 3) ~= 0) && mod(i, 10) ~= 5 || i == 2 || i == 3 || i == 5 % We only need to consider odd integers,
                % integers in which the sum of the digits of the number is not divisible by 3, integers that are not divisible by 5, and the numbers 2, 3, & 5 (the first few primes).
                j = 7;
                while j < i/(j - 2) && cnt == 0 % Execute the loop while j < i/(j - 2) and while cnt = 0 (i.e. no factors of i have been found).
                    % The reason for dividing i by j - 2 is the following:
                    % If j is not a factor of i, then it's guaranteed that i will not have any factors larger than i(j - 2).   
                    % Take 25, for example.  j = 3 is not a factor of 25,
                    % so any number greater than 25/3 = 8.33 cannot be a
                    % factor of 25. j = 4 is not a factor of 25, so any
                    % number grater than 25/4 = 6.25 cannot be a factor of
                    % 25.  Of course, 5 is a factor of 25.
                    if mod(i, j) == 0 % Check if i/j has a remainder.  If it doesn't, then i is not prime and cnt set equal to one.
                        cnt = 1;
                    end
                    j = j + 2; % Increment j to the next odd number for the next iteration of the while loop.
                end
                if cnt == 0 % If the while loop completes and cnt = 0, then i is prime.
                    x = x + 1; % Increment x which is used to index the vector of prime numbers.
                    primes(x) = i; % Add i to the list of prime numbers.
                end
            end
        end
        f = primes; % Output the vector of all prime numbers found.
    else
        f = 'ERROR: a and b in primes(a, b) must be positive integers with b > a.'; % Error messgae if invalid inputs were entered.
    end
end
