Getting odd results when trying to solve Collatz p‌r‌o‌b‌l‌e‌m

StackOverflow https://stackoverflow.com/questions/12021254

  •  27-06-2021
  •  | 
  •  

質問

I'm trying to solving Project Euler Problem 14. 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.

#include <iostream>
#include <vector>
using namespace std;

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

    vector<int> v;
    v.push_back(0);
    v.push_back(0);

    for(int i = 1; i < 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<int>::iterator it;

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

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

int main()
{
    find_longest(100);
    //find_longest(1000000);
}
役に立ちましたか?

解決

//removing change for type mismatch

You don't need to remember all N numbers in a vector. All you need is current sequence length. Then you calculate sequence length for the next number and if it is bigger than what you have already, you just keep the biggest one.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top