Getting odd results when trying to solve Collatz problm
<p>I'm trying to solving #14 on project euler.  It asks to find the number under 1 million that generates the longest sequence.  What I did was create a vector, v, and populate its elements with the length of the sequence for a particular number.  Thus, the element that resides in position 13 will correspond to the length of the sequence generated by the number 13, and so on.  However, some seemingly random elements take very large numbers and I can't figure out what's wrong with the code.  Also, when I test it with 1,000,000, I get a completely wrong answer, but I know the program is working for some small numbers after testing them by hand and verifying.</p>

<p>Any insight would be awesome.  Thanks.</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;vector&gt;
using namespace std;

void find_longest(int n)
{
    int count = 1;
    int max = 0;
    int position;

    vector&lt;int&gt; v;
    v.push_back(0);
    v.push_back(0);

    for(int i = 1; i &lt; n; i++)
    {
        long long int trainer = i;
        count = 1;
        while(trainer != 1)
        {
            if(trainer%2 == 0)
            {
                trainer /= 2;
                count++;
            }
            else
            {
                trainer = 3*trainer + 1;
                count++;
            }
        }
        v.push_back(count);
    }

    vector&lt;int&gt;::iterator it;

    for(it = v.begin(); it &lt; v.end(); it++)
    {
        cout &lt;&lt; v[*it] &lt;&lt; endl;
        //if(v[*it] &gt; max)
        //{
        //    max = v[*it];
        //    position = *it;
        //}
    }

    //cout &lt;&lt; "The longest sequence is " &lt;&lt; max &lt;&lt; " terms long and is ";
    //cout &lt;&lt; "generated by the number " &lt;&lt; position &lt;&lt; "." &lt;&lt; endl;
}

int main()
{
    find_longest(100);
    //find_longest(1000000);
}
</code></pre>
