Skip to content

Instantly share code, notes, and snippets.

@SeanCline
Created September 12, 2013 12:12
Show Gist options
  • Save SeanCline/6536371 to your computer and use it in GitHub Desktop.
Save SeanCline/6536371 to your computer and use it in GitHub Desktop.
#include <stdexcept>
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono;
typedef long long number;
typedef int count_type;
number getNext(number n)
{
if (n <= 1) {
throw invalid_argument("Number must be greater than 1.");
}
if (n%2 == 0) { // Even
return n/2;
} else { // Odd
return 3*n+1;
}
}
count_type countChain(number n)
{
count_type count = 1;
while ((n = getNext(n)) != 1) {
++count;
}
return count;
}
int main()
{
auto beginTime = std::chrono::high_resolution_clock::now();
number maxStart = 0;
count_type maxCount = 0;
for (number i = 2; i < 1000000; ++i)
{
count_type currCount = countChain(i);
if (currCount > maxCount) {
maxCount = currCount;
maxStart = i;
}
}
auto endTime = std::chrono::high_resolution_clock::now();
cout << "The number that starts the longest chain is " << maxStart << " with a chain totaling " << maxCount << " elements. "
<< "It was found in " << std::chrono::duration_cast<milliseconds>(endTime - beginTime).count() << "ms." << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment