Uva Online Judge problem 100, 3n + 1 I am having a tough time submitting this code to UVa Online judge and having it pass. I keep getting the message - Your program used more CPU time than what is allowed for this problem. That means that your algorithm is not fast enough or that it entered into an infinite loop.

The challenge: for each line of input, which contains two integers i and j, find the length of the longest collatz-sequence for all Collatz sequences starting with i, i + 1, i + 2, …, j.  You can assume that no operation overflows a 32-bit integer.

I have no idea where the problem is! Any help would be appreciated. Also, I am trying to analyze the algorithm, and I believe it should be O(n2).

 #include &lt;iostream&gt;
    using namespace std;

    int cycleLength(int n) {
      int i = 1;  

      while (n != 1) {
        if (n % 2 == 0) {
          n = n/2;
        } else {
          n = 3*n + 1;
        }
        i++;
      }
      return i;
    }

    int main() {

      int fOriginal, sOriginal;
      int first, second, max, temp;

     while (cin &gt;&gt; fOriginal &gt;&gt; sOriginal) {

        if (fOriginal &gt; sOriginal) {
          temp = fOriginal;
          first = sOriginal;
          second = temp;
        }

        max = cycleLength(first); 

        for(int i = first + 1; i &lt;= second; i++) {
          temp = cycleLength(i);
          if (temp &gt; max) {
            max = temp;
          }
        }

        cout &lt;&lt; fOriginal &lt;&lt; " " &lt;&lt; sOriginal &lt;&lt; " " &lt;&lt; max &lt;&lt; endl;
      }

      return 0;
    }
For each number in a first, second range you count how long does the sequence take to reach 1. It is definitely too much of the work: you'd surely encounter same numbers over and over again. Instead of recalculating sequence tails for them, it is much faster to remember and reuse such intermediate results. Since it is a contest problem I am not going to share any code.

Also, I am very interested in how did you come up with \$O(n^2)\$.