CoffeeScriptでProject Euler #14

Problem14

正の整数に以下の式で繰り返し生成する数列を定義する。

n → n/2 (n が偶数)

n → 3n + 1 (n が奇数)

13からはじめるとこの数列は以下のようになる。
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

13から1まで10個の項になる。 この数列はどのような数字からはじめても最終的には 1 になると考えられているが、まだそのことは証明されていない(コラッツ問題)

さて、100万未満の数字の中でどの数字からはじめれば一番長い数列を生成するか。

注意: 数列の途中で100万以上になってもよい

http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%2014

Solution

collatz = (x) ->
  t = x
  cnt = 0
  while(x != 1)
    if x % 2 == 0
      x /= 2
    else
      x = 3*x + 1
    cnt++
  return [t, cnt]

Array::max = ->
  Math.max.apply Math, this

maxIndex = (ts) ->
  m = 0
  index = 0
  for t in ts
    if t[1] > m
      index = t[0]
      m = t[1]
  return index

console.log maxIndex (collatz(x) for x in [1..1000000])

順路:CoffeeScriptでProject Euler #15
逆路:CoffeeScriptでProject Euler #13