1

This is a problem for an online judge. It takes two inputs, i and j where the largest 3n+1 cycle length has to be found between the two inputs.

The program should terminate when x becomes 1. But when it is 1, the code does not terminate but continues to loop 1. Thanks in advance for any help.

#include <iostream>

using namespace std;

int main(){
    int i, j, temp_i, temp_j, counter, max;

    max = 0;

    cin >> i >> j;

    temp_i = i;
    temp_j = j;

    for(int x = i; x < j; x++){
        counter = 1;
        while(x != 1){
            if(x % 2 == 0){
                x = x/2;
                // cout << x << endl;
            }
            else{
                x = 3*x + 1;
            }
            counter++;
        }
        if(counter > max){
            max = counter;
        }
    }

    cout << temp_i << " " << temp_j << " " << max << endl;

    return 0;
}
1
  • Are you sure that x becomes 1 at any time? It looks like it can possibly diverges to infinity. Commented Jun 17, 2015 at 4:46

1 Answer 1

1

You have a logical error regarding your loops. Think about this: When x == 1 and the inner loop ends, then x is increased to 2 and the inner loop runs again until x == 1 when x is increased to 2 and the inner loop runs again... And so on and so on.

You need to use a second variable for the outer loop counting. Something like

for (int y = i; y < j; ++y)
{
    int x = y;
    while (x != 1)
    {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.