2

I have this section of code that's supposed to find the Collatz sequence of all integers in a given range, defined by user input. The problem is that in the for loop, current_number never gets incremented, or in the inner while loop, current_number != 1 never fails. What am I missing?

while (lower != 0 && upper != 0) {
    cout << "Lower bound (integer): ";
    cin >> lower;
    cout << "Upper bound (integer): ";
    cin >> upper;
    if (lower == 0 || upper == 0)
        return 0;
    for (current_number = lower; current_number <= upper;
        ++current_number) {
            //cout << current_number << endl;
            counter = 0;
            sequence = sequence + to_string(current_number) + ", ";
            while (current_number != 1) {
                if (current_number % 2 == 0) {
                    current_number = current_number / 2;
                    sequence = sequence + to_string(current_number) + ", ";
                }
                else {
                    current_number = current_number * 3 + 1;
                    sequence = sequence + to_string(current_number) + ", ";
                }
                cout << current_number << endl;
                ++counter;
            }
            //if (counter > longest) {
            //  longest = counter;
            //  the_longest_seed = current_number;
            //}
    }
    cout << sequence << endl;

}
spartanhooah
  • 183
  • 4
  • 15

3 Answers3

7

current_number % 2 == 0 is true for all current_number = 0, 2, 4, 6, ....

When this happens, you set current_number to be current_number / 2.. So when current_number is 2, you're setting it to 1, then you increment it (++current_number), then it's 2 again (!= 1), so you'll enter the while loop, then because 2 % 2 = 0 you'll set it to 1 again.. And so on.. :_(

Tip for life: Debug your code, it'll save time, efforts and sometimes money too.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • How do you mean to debug? I had tried putting some output statements in, but that wasn't helping me figure out where things went south. If you mean debug using the IDE (MSVC 2013 RC in my case), then I don't know how to do that yet. – spartanhooah Sep 17 '13 at 16:57
0

Concerning never-failing loop. If current_number != 1 and it is not 2 (if it is, the other guy has answered), it goes into the while loop and never ends, because...

Let's say it is 3:

3 % 2 != 0, so it becomes 10,

10 % 2 == 0, so it becomes 5,

5 %2 != 0, so it becomes 16

...

Never fails.

khajvah
  • 4,889
  • 9
  • 41
  • 63
0

Next to the other error, you are also using current_number to iterate over the input-range and you're changing it to output your Collatz sequence. You should change a copy of current_number.

stefaanv
  • 14,072
  • 2
  • 31
  • 53