I've solved a 3*N + 1 problem (100) on UVa Online Judge but here's one thing that I don't understand, but it has something to do with Java, I guess, not with the algorithm itself. So here's the code:
private static int maxCycleLength(int lo, int hi) {
maxLength = 0;
int n = 0;
int length = 0;
for (int i = lo; i <= hi; i++) {
// It's the first time we're computing the cycle length for n
if (lengths[i] == 0) {
n = i;
length = 1;
while (n != 1) {
if ((n % 2) == 0) {
n = n >> 1;
length++;
}
else {
n = 3 * n + 1;
n = n >> 1;
length += 2;
}
}
lengths[i] = length;
}
// Otherwise we just look it up
else
length = lengths[i];
// Check if the current cycle length is the maximum
if (length > maxLength)
maxLength = length;
}
return maxLength;
What I don't understand: My IDE (IDEA) tells me that in this piece of code the initialisation of variables n and lengthis redundant, however, maxLength must be initialised and if I don't do it, it does not compile.
Why so? How is maxLength different here from n and length?
int length;just afterfor {andint n : i;