Reputation: 192
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;
}
Upvotes: 2
Views: 568
Reputation: 5090
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.
Upvotes: 0
Reputation: 95978
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.
Upvotes: 7
Reputation: 14392
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
.
Upvotes: 0