Project Euler その12

Problem14

The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.

以下に示す再帰的手続きは正の整数に対して定義されている。

n → n/2 (nが偶数のとき)
n → 3n + 1 (nが奇数のとき)

この規則のもとに13から始めると、次のような数列を得る。

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
この13から始まって1で終わる数列は10個の項を含んでいる。であるが、すべての数は1で終わるとされるコラッツ予想を証明するにはまだ至らない。

100万以下のどの数が最も長いチェーンを生成するだろうか?

コード

C = 0
def collatz(N):
    global C
    C+=1
    if N == 1:
        return
    if N%2 == 0: collatz(N/2)
    else: collatz(3*N+1)

max = 0
i_max = 0
for i in range(1,1000000):
    collatz(i)
    if max < C:
        max = C
        i_max = i
    C = 0

print i_max

再帰回数出すためにglobal使うのはアホらしいなぁ・・・
なにかいい手があるのかも