Comment detail
コラッツ・角谷の問題 (Nested Flatten)Listではなく、ただの配列でキャッシュを実装するとかなり高速化できますね。 PentiumM 2GHz/Windows XP (32bit)で125msでした。 C:¥>java Dk120 f(837799)=524 in 125 ms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class Dk120 {
static final int maxN = (1 << 20);
static final int cacheN = maxN;
private static int[] cache = new int[cacheN+1];
private static int colatz(long n) {
if (n == 1) return 0;
if (n <= cacheN && cache[(int)n] != 0) return cache[(int)n];
int c = 1 + ((n % 2 == 0) ? colatz(n >> 1) : colatz(n * 3 + 1));
if (n <= cacheN) cache[(int)n] = c;
return c;
}
public static void main(String[] args) {
int max = 1;
int maxValue = 0;
long start = System.currentTimeMillis();
for (int i = 1; i <= maxN; i++) {
int c = colatz(i);
if (max < c) { max = c; maxValue = i; }
}
System.out.printf("f(%d)=%d in %d ms", maxValue, max, System.currentTimeMillis() - start);
}
}
|




malark #5127() [ Java ] Rating0/0=0.00
Rating0/0=0.00-0+
1 reply [ reply ]