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
28
29
30
31
32
33
34
35
36
37
38
39
using System;
class Class1 {
    static uint MAX = Convert.ToUInt32(Math.Pow(2, 20));
    static int max3Plus1 = (int)MAX * 3 + 1;
    static int[] cache = new int[max3Plus1];

    static void Main() {
        long start = DateTime.Now.Ticks;
        int maxStep = 0;
        uint maxN = 0;
        for(uint n = 1; n <= MAX; n++) {
            int step = collatz(n);
            if(maxStep < step) {
                maxStep = step;
                maxN = n;
            }
        }
        Console.WriteLine("f(" + maxN + ")=" + maxStep);
        Console.WriteLine((DateTime.Now.Ticks - start) / 10000L + "ms");
        Console.ReadLine();
    }

    static int collatz(uint n) {
        int step = 0;
        uint z = n;
        while(z != 1) {
            if(z - 1 <= max3Plus1 && cache[z - 1] != 0) {
                step += cache[z - 1];
                break;
            } else {
                if(z % 2 == 0) z /= 2;
                else z = z * 3 + 1;
                step++;
            }
        }
        cache[n - 1] = step;
        return step;
    }
}