diff --git a/headers/Problems/Problem1.hpp b/headers/Problems/Problem1.hpp index eb0a610..5abbaed 100644 --- a/headers/Problems/Problem1.hpp +++ b/headers/Problems/Problem1.hpp @@ -38,6 +38,7 @@ private: static uint64_t MAX_NUMBER; //The highest number to be tested //Instance variables uint64_t fullSum; //For the sum of all the numbers + uint64_t sumOfProgression(uint64_t multiple); //Gets the sum of the progression of the multiple public: //Constructor Problem1(); @@ -51,7 +52,7 @@ public: /* Results: The sum of all the numbers < 1000 that are divisible by 3 or 5 is 233168 -It took an average of 957.000 nanoseconds to run this problem over 100 iterations +It took an average of 50.000 nanoseconds to run this problem over 100 iterations */ #endif //PROBLEM1_HPP diff --git a/src/Problems/Problem1.cpp b/src/Problems/Problem1.cpp index 33af4a5..fcfb6bb 100644 --- a/src/Problems/Problem1.cpp +++ b/src/Problems/Problem1.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include "Problems/Problem1.hpp" @@ -36,6 +37,12 @@ uint64_t Problem1::MAX_NUMBER = 999; Problem1::Problem1() : Problem("What is the sum of all the multiples of 3 or 5 that are less than 1000?"), fullSum(0){ } +uint64_t Problem1::sumOfProgression(uint64_t multiple){ + uint64_t numTerms = std::floor(MAX_NUMBER / 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 + return ((numTerms / 2.0) * (multiple + (numTerms * multiple))); +} + //Operational functions //Solve the problem void Problem1::solve(){ @@ -46,16 +53,8 @@ void Problem1::solve(){ //Start the timer timer.start(); - //Step through every number < 1000 and see if either 3 or 5 divide it evenly - for(uint64_t cnt = 1;cnt <= MAX_NUMBER;++cnt){ - //If either 3 or 5 divides it evenly then add it to the vector - if((cnt % 3) == 0){ - fullSum += cnt; - } - else if((cnt % 5) == 0){ - fullSum += cnt; - } - } + //Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap + fullSum = sumOfProgression(3) + sumOfProgression(5) - sumOfProgression(3 * 5); //Stop the timer timer.stop();