diff --git a/ProjectEuler/C++/Problem12.cpp b/ProjectEuler/C++/Problem12.cpp index 3ee0185..57da816 100644 --- a/ProjectEuler/C++/Problem12.cpp +++ b/ProjectEuler/C++/Problem12.cpp @@ -1,38 +1,53 @@ -#include -#include -#include +//ProjectEuler/C++/Problem12.cpp +//Matthew Ellison +// Created: 9-27-18 +//Modified: 9-28-18 +//This file contains the program to calculate the answer to Problem 12 on ProjectEuler.net + +#include +#include //For fmod +#include //For the timer + + +//Counter how many divisors number has unsigned long countDivisors(unsigned long number); + int main(){ - bool found = false; - unsigned long sum = 1; - unsigned long counter = 2; - const unsigned long goalDivisors = 500; + bool found = false; //To flag whether the number has been found + unsigned long sum = 1; //The sum of the numbers up to counter + unsigned long counter = 2; //The next number to be added to sum + const unsigned long goalDivisors = 500; //The number of divisors that is being sought std::chrono::high_resolution_clock::time_point startTime = std::chrono::high_resolution_clock::now(); while(!found){ + //If the number of divisors is correct set the flag if(countDivisors(sum) > goalDivisors){ found = true; } + //Otherwise add to the sum and increase the next numeber else{ sum += counter; ++counter; } } std::chrono::high_resolution_clock::time_point endTime = std::chrono::high_resolution_clock::now(); - --counter; - std::cout << "The triangular number " << sum << " is made with all number >= " << counter << " and has " << countDivisors << " divisors" << std::endl; + //Print the results + std::cout << "The triangular number " << sum << " is made with all number >= " << counter - 1 << " and has " << countDivisors << " divisors" << std::endl; std::cout << "The problem took " << std::chrono::duration_cast(std::chrono::high_resolution_clock::duration(endTime - startTime)).count() << " milliseconds" << std::endl; return 0; } + unsigned long countDivisors(unsigned long number){ - unsigned long numDivisors = 0; - for(int cnt = 0;cnt * cnt < number;++cnt){ - //if((number % cnt) == 0){ + unsigned long numDivisors = 0; //Holds the number of divisors + //You only need to go to sqrt(number). cnt * cnt is faster than sqrt() + for(int cnt = 1;cnt * cnt < number;++cnt){ + //Check if the counter evenly divides the number + //If it does the counter and the other number are both divisors if(fmod((double)number, (double)cnt) == 0){ numDivisors += 2; }