mirror of
https://bitbucket.org/Mattrixwv/octavefunctions.git
synced 2025-12-06 18:53:57 -05:00
59 lines
1.9 KiB
C++
59 lines
1.9 KiB
C++
//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 <iostream>
|
|
#include <cmath> //For fmod
|
|
#include <chrono> //For the timer
|
|
|
|
|
|
//Counter how many divisors number has
|
|
unsigned long countDivisors(unsigned long number);
|
|
|
|
|
|
int main(){
|
|
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();
|
|
|
|
//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::milliseconds>(std::chrono::high_resolution_clock::duration(endTime - startTime)).count() << " milliseconds" << std::endl;
|
|
|
|
std::cin.get();
|
|
|
|
return 0;
|
|
}
|
|
|
|
|
|
unsigned long countDivisors(unsigned long number){
|
|
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;
|
|
}
|
|
}
|
|
return numDivisors;
|
|
}
|