Files
ProjectEulerOctave/Problem5.m

80 lines
2.2 KiB
Matlab

%ProjectEuler/Octave/Problem5.m
%Matthew Ellison
% Created: 03-16-19
%Modified: 03-28-19
%What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
%{
Copyright (C) 2019 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
%}
%Create your variables
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;
%Start the timer
startTime = clock();
%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
%Stop the timer
endTime = clock();
%Print the results
printf("The smallest positive number that is evenly divisible by all numbers 1-20 is %d\n", prod(factors))
printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime))
%Cleanup your variables
clear counter;
clear factorCnt;
clear listCnt;
clear list;
clear nums;
clear factors;
clear startTime;
clear endTime;
clear ans;
%{
Results:
The smallest positive number that is evenly divisible by all numbers 1-20 is 232792560
It took 0.010742 seconds to run this algorithm
%}