Add tags

Add tags to the following comment
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);
    }    
}

Add tags

The input will be splited to tags with space.

Index

Feed

Other

Link

Pathtraq

loading...