Files
OctaveFunctions/ProjectEuler/Problem5.m

46 lines
1.2 KiB
Matlab

%ProjectEuler/Problem5.m
%This is a script to answer Problem 5 for Project Euler
%What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
%Create your variables
value = 0; %The value that is evenly divisible
nums = [1:20];
factors = [1]; %The factors that are already in the number
list = []; %For a temperary list of the factors of the current number
counter = 1;
%You need to find the factors of all the numbers from 1->20
while(counter <= size(nums)(2))
list = factor(nums(counter));
%Search factors and try to match all elements in list
listCnt = 1;
factorCnt = 1;
while(listCnt <= size(list)(2))
if((factorCnt > size(factors)(2)) || (factors(factorCnt) > list(listCnt)))
%If it was not found add the factor to the list for the number and reset the counters
factors(end + 1) = list(listCnt);
factors = sort(factors);
factorCnt = 1;
listCnt = 1;
elseif(factors(factorCnt) == list(listCnt))
++listCnt;
++factorCnt;
else
++factorCnt;
end
end
++counter;
end
%Cleanup your variables
clear counter;
clear factorCnt;
clear listCnt;
clear list;
clear nums;
clear ans; %Appears whenever you use increment
value = prod(factors);
value