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
%Matthew Ellison
% Created:
%Modified: 03-28-19
% Created: 03-28-19
%Modified: 10-26-20
%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
it under the terms of the GNU Lesser General Public License as published by
@@ -21,42 +22,32 @@
%}
%Setup your variables
fullSum = 0; %To hold the sum of all the numbers
numbers = 0; %To hold all of the numbers
counter = 0; %The number. It must stay below 1000
%Setup your variables
fullSum = 0; %To hold the sum of all the numbers
numbers = 0; %To hold all of the numbers
counter = 0; %The number. It must stay below 1000
%Start the timer
startTime = clock();
%Start the timer
startTime = clock();
%When done this way it removes the possibility of duplicate numbers
while(counter < 1000)
%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
%Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap
sumOfMultiples = sumOfProgression(3) + sumOfProgression(5) - sumOfProgression(3 * 5);
%Increment the number
++counter;
end
%Stop the timer
endTime = clock();
%Stop the timer
endTime = clock();
%Print the results
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))
%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("It took %f seconds to run this algorithm\n", etime(endTime, startTime))
end %End of Problem1()
%Cleanup your variables
clear fullSum;
clear numbers;
clear counter;
clear startTime;
clear endTime;
clear ans;
%Gets the sum of the progression of the multiple
function [sum] = sumOfProgression(multiple)
numTerms = floor(999 / multiple); %This gets the number of multiples of a particular number that is < MAX_NUMBER
%The sum of progression formula is (n / 2)(a + l). n = number of terms, a = multiple, l = last term
sum = ((numTerms / 2) * (multiple + (numTerms * multiple)));
end %End of sumOfProgression
%{
Results: