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 <iostream>
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 >> fOriginal >> sOriginal) {
if (fOriginal > sOriginal) {
temp = fOriginal;
first = sOriginal;
second = temp;
}
max = cycleLength(first);
for(int i = first + 1; i <= second; i++) {
temp = cycleLength(i);
if (temp > max) {
max = temp;
}
}
cout << fOriginal << " " << sOriginal << " " << max << endl;
}
return 0;
}