Updated problem 1 algorithm

This commit is contained in:
2020-10-26 14:44:44 -04:00
parent e637233dd8
commit 57c3fa5b43

View File

@@ -1,10 +1,11 @@
function [] = Problem1()
%ProjectEuler/Octave/Problem1.m %ProjectEuler/Octave/Problem1.m
%Matthew Ellison %Matthew Ellison
% Created: % Created: 03-28-19
%Modified: 03-28-19 %Modified: 10-26-20
%What is the sum of all the multiples of 3 or 5 that are less than 1000 %What is the sum of all the multiples of 3 or 5 that are less than 1000
%{ %{
Copyright (C) 2019 Matthew Ellison Copyright (C) 2020 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -29,34 +30,24 @@ counter = 0; %The number. It must stay below 1000
%Start the timer %Start the timer
startTime = clock(); startTime = clock();
%When done this way it removes the possibility of duplicate numbers %Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap
while(counter < 1000) sumOfMultiples = sumOfProgression(3) + sumOfProgression(5) - sumOfProgression(3 * 5);
%See if the number is a multiple of 3
if(mod(counter, 3) == 0)
numbers(end + 1) = counter;
%See if the number is a multiple of 5
elseif(mod(counter, 5) == 0)
numbers(end + 1) = counter;
end
%Increment the number
++counter;
end
%Stop the timer %Stop the timer
endTime = clock(); endTime = clock();
%Print the results %Print the results
printf("The sum of all the numbers less than 1000 that is divisibly by 3 or 5 is: %d\n", sum(numbers)) printf("The sum of all the numbers less than 1000 that is divisibly by 3 or 5 is: %d\n", sumOfMultiples)
printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime)) printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime))
%Cleanup your variables end %End of Problem1()
clear fullSum;
clear numbers; %Gets the sum of the progression of the multiple
clear counter; function [sum] = sumOfProgression(multiple)
clear startTime; numTerms = floor(999 / multiple); %This gets the number of multiples of a particular number that is < MAX_NUMBER
clear endTime; %The sum of progression formula is (n / 2)(a + l). n = number of terms, a = multiple, l = last term
clear ans; sum = ((numTerms / 2) * (multiple + (numTerms * multiple)));
end %End of sumOfProgression
%{ %{
Results: Results: