Skip to content

Instantly share code, notes, and snippets.

@joshrendek
Last active December 14, 2015 09:59
Show Gist options
  • Save joshrendek/5069110 to your computer and use it in GitHub Desktop.
Save joshrendek/5069110 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <map>
#include <iterator>
#include <math.h>
#include <unistd.h>
using namespace std;
std::map<int, int> Cache;
std::map<int, int>::iterator it;
int calculate_collatz(int num)
{
int counter = 1;
unsigned long int curr = num;
while(true)
{
// it = Cache.find(curr);
// if(it != Cache.end())
// {
// counter += Cache.find(curr)->second;
// return counter;
// }
if(curr == 1)
{
break; // base case
counter++;
}
if(curr % 2 == 0) // even
{
curr = curr / 2;
counter++;
}
else
{
curr = 3*curr + 1;
counter++;
}
}
return counter;
}
int main(int argc, char *argv[])
{
int count = 0;
int biggest_num = 0;
int num = 13;
while(true)
{
int result = calculate_collatz(num);
Cache.insert(std::make_pair(num, result));
if(result > count)
{
biggest_num = num;
count = result;
// cout << "Biggest number: " << biggest_num << " with " << count << " terms" << endl;
}
num++;
// if (num > 50) break;
if (num > 1000000) break;
}
cout << "Biggest number: " << biggest_num << " with " << count << " terms" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment