Problem 14 von http://projecteuler.net
“Which starting number, under one million, produces the longest chain?”
Mit dieser Vorgabe
n is even -> n/2 n is odd -> 3n + 1 n is 1 -> 1
lässt sich natürlich wunderbar eine rekursive Lösung implementieren.
Hier meine Lösung dazu:
public class Problem14 {
private static int length = 0;
public static void main(String[] args) {
long result = 0;
int terms = 0;
for (long i = 1; i < 1000000; i++) {
collatz(i);
if (terms < length) {
result = i;
terms = length;
}
length = 0;
}
System.out.println("Ergebnis: " + result);
}
private static int collatz(long n) {
length++;
if (n == 1) {
return 1;
} else if (n % 2 == 0) {
return collatz(n / 2);
} else {
return collatz(3 * n + 1);
}
}
}
Ergebnis: 837799
