Files
ProjectEulerCPP/Source/Problem6.cpp

97 lines
2.9 KiB
C++

//ProjectEuler/C++/Source/Problem6.cpp
//Matthew Ellison
// Created: 09-28-18
//Modified: 07-14-19
//Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/myClasses
/*
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/>.
*/
#include <cinttypes>
#include <cmath>
#include <string>
#include <sstream>
#include "Stopwatch.hpp"
#include "../Headers/Problem.hpp"
#include "../Headers/Problem6.hpp"
int Problem6::START_NUM = 1;
int Problem6::END_NUM = 100;
Problem6::Problem6() : Problem("Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum."), sumOfSquares(0), squareOfSum(0){
}
void Problem6::solve(){
//If the problem has already been solved do nothing and end the function
if(solved){
return;
}
//Start the timer
timer.start();
//Run through all numbers and add them to the appropriate sums
for(int currentNum = START_NUM;currentNum <= END_NUM;++currentNum){
sumOfSquares += (currentNum * currentNum); //Add the square to the correct variable
squareOfSum += currentNum; //Add the number to the correct variable for squaring later
}
//Square the sum that needs it
squareOfSum *= squareOfSum;
//Stop the timer
timer.stop();
//Throw a flag to show the problem is solved
solved = true;
}
std::string Problem6::getString() const{
//If the problem hasn't been solved throw an exception
if(!solved){
throw unsolved();
}
std::stringstream results;
results << "The difference between the sum of the squares and the square of the sum of all numbers from 1-100 is " << abs(sumOfSquares - squareOfSum);
return results.str();
}
uint64_t Problem6::getSumOfSquares() const{
//If the problem hasn't been solved throw an exception
if(!solved){
throw unsolved();
}
return sumOfSquares;
}
uint64_t Problem6::getSquareOfSum() const{
//If the problem hasn't been solved throw an exception
if(!solved){
throw unsolved();
}
return squareOfSum;
}
uint64_t Problem6::getDifference() const{
//If the problem hasn't been solved throw an exception
if(!solved){
throw unsolved();
}
return abs(sumOfSquares - squareOfSum);
}