Problem
The following iterative sequence is defined for the set of positive integers:
n n/2 (n is even)
n 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13
40
20
10
5
16
8
4
2
1









It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
Code
#include <iostream>
using namespace std;
int upper(int num)
{
cout << num << endl;
if (num > 1000 && num != 0)
{
return num;
}
if ((num-1)%3 == 0)
{
num = (num-1);
}
else
{
num<<=1;
}
return upper(num);
}
int getChainCount(unsigned int num)
{
int count = 0;
while (num != 1)
{
int t = num & 1;
if (t == 0)
{
num >>= 1;
}
else
{
num = 3*num + 1;
}
//cout << num << ",";
count++;
}
cout << endl;
return ++count;
}
int main()
{
int maxCount = 0;
int maxNum = 0;
//getChainCount(72);
for (unsigned int a = 999999; a != 1; a-=2)
{
//cout << "[" << a << "]:";
int b = getChainCount(a);
if (b > maxCount)
{
maxCount = b;
maxNum = a;
}
}
cout << maxNum << endl;
}