我的C ++程序没有跟踪我的3n + 1最长序列

时间:2017-04-16 20:16:50

标签: c++

如果输入1然后是5,则此代码的最终输出是......

  

起始值在[1,5]范围内的最长序列有8个元素。

但相反,我得到{16个元素}。

我相信这个问题可能出在我的柜台系统上,并且会回来。有没有人对如何解决这个问题有任何建议?

#include <iostream>

using namespace std;
// Functions
void getUserInput(int &start, int &end);
int longestSequence(int minimum, int maximum);
int getNextElement(int x);
string generateSequence(); // still need to write definition
int counter = 1;

int main()
{
    int minimum;
    int maximum;
    int last;

    getUserInput(minimum, maximum); // 
    last = longestSequence(minimum, maximum); // starts longest sequence counter 

    cout << "The longest sequence with a start value in the range [" << minimum
         << ", " << maximum << "] has " << last << " elements." << endl;

    return 0;
}

void getUserInput(int &start, int &end)
{
    cout << "Enter the min of the range for the sequence to start " << endl;
    cin >> start;
    cout << "Enter the max of the range for the sequence to start " << endl;
    cin >> end;
}

int getNextElement(int x) // // This function does the 3n+1 computation
{

    if (x != 1) // Checks for the end of the sequence. The end being when the number is 1.
    {
        counter++;
        if (x % 2 == 0) // checks if its even
            getNextElement(x / 2); // takes the new number through the function again
        else
            getNextElement(x * 3 + 1); // takes the new number into the function again
    }
    cout << "This is in getNextElement" << counter << endl;
    return counter; // this is returned as length in the longestSequence function.
}

int longestSequence(int minimum, int maximum) // this function compares all the sequence lengths within the range of minimum and maximum.
{
    int max = 0; // Longest seqence

    for (int i = minimum; i <= maximum; i++)
    {
        int length = getNextElement(i); // length is a temp that will hold the longest seqence

        if (length > max) // this loop validates if the newest "length" from the sequence is bigger than the previous one

            cout << "This is in the longest sequence loop ... length" << length
                 << endl;
        cout << "This is in the longest sequence loop AS MAX" << length << endl;
        max = length; // after the first run of the loop, max stores the longest seqence, and updates it after each run of the for loop if its longer
        // counter = 1; not sure why this is here
    }
    cout << "This is in longest sequence.... max " << max << endl;
    return max;
}

1 个答案:

答案 0 :(得分:3)

在致电int length = getNextElement(i)之前将您的计数器重置为1。 您获得16作为输出,因为每次调用getNextElement(i)都会从最后一个函数调用的位置恢复counter

counter=1;
int length = getNextElement(i);

正如你在自己的代码中错过了

// counter = 1; not sure why this is here

另外,max不会更新到更大的长度,而是任何长度,因为它超出了if的范围,用于检查更大的长度。因此,为if条件添加大括号并在其中移动max=length