Files
ProjectEulerCPP/Source/Problem1.cpp

96 lines
2.6 KiB
C++

//ProjectEuler/ProjectEulerCPP/Source/Problem1.cpp
//Matthew Ellison
// Created: 07-10-19
//Modified: 07-09-20
//What is the sum of all the multiples of 3 or 5 that are less than 1000
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/myClasses
/*
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
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/>.
*/
#include <string>
#include <sstream>
#include <cinttypes>
#include <vector>
#include "Stopwatch.hpp"
#include "../Headers/Problem.hpp"
#include "../Headers/Problem1.hpp"
//The highest number to be tested
uint64_t Problem1::MAX_NUMBER = 999;
//Constructor
Problem1::Problem1() : Problem("What is the sum of all the multiples of 3 or 5 that are less than 1000?"), fullSum(0){
}
//Operational functions
//Solve the problem
void Problem1::solve(){
//If the problem has already been solved do nothing and end the function
if(solved){
return;
}
//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;
}
}
//Stop the timer
timer.stop();
//Throw a flag to show the problem is solved
solved = true;
}
//Reset the problem so it can be run again
void Problem1::reset(){
Problem::reset();
fullSum = 0;
}
//Gets
//Return a string with the solution to the problem
std::string Problem1::getString() const{
//If the problem hasn't been solved throw an exception
if(!solved){
throw unsolved();
}
//Create a string with the results and return it
std::stringstream results;
results << "The sum of all the numbers < " << MAX_NUMBER + 1 << " that are divisible by 3 or 5 is " << fullSum;
return results.str();
}
uint64_t Problem1::getSum() const{
//If the prblem hasn't been solved throw an exception
if(!solved){
throw unsolved();
}
return fullSum;
}