CoffeeScriptでProject Euler #5

Problem 5

2520 は 1 から 10 の数字の全ての整数で割り切れる数字であり、そのような数字の中では最小の値である。

では、1 から 20 までの整数全てで割り切れる数字の中で最小の値はいくらになるか。

Strategy

20以下の素数を列挙→それぞれの素数について20以下で最大となるべき乗を取る(2なら2^4<=20, 3^2<=20, 5^1<=20,...)→できたすべての数を掛け合わせる。
Project Eulerに挑戦: 問題5 の手作業による解法に近いアプローチ。

Solution

max = 20

Array::product = ->
  this.reduce (a, b) -> a * b

is_prime ?= (n) -> [2..n-1].every? ( (x) -> n % x != 0 )

prime_numbers = (x) ->
  [2].concat [2..x].filter (n) -> is_prime? n

list = (prime_numbers max).map (x) ->
  while x*x < max
    x *= x
  x

console.log list.product()

順路:CoffeeScriptでProject Euler #6
逆路:CoffeeScriptでProject Euler #4