読者です 読者をやめる 読者になる 読者になる

mu chance or much chance ?

日々の戯れ言

Project Euler 53

Project Euler

Problem53を解きました.

  • Combinatoric selections

There are exactly ten ways of selecting three from five, 12345:

123, 124, 125, 134, 135, 145, 234, 235, 245, and 345

In combinatorics, we use the notation, 5C3 = 10.

In general,

nCr = n! / r!(n−r)! ,where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.

How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than one-million?

https://projecteuler.net/problem=53

問題は「1 ≤ n ≤ 100 について,100万を超える nCr は何通りか求めよ.」.

c = [1, 1]
n = 100
count = 0

(n - 1).times do
  c2 = []
  c2.push(1)
  (c.length - 1).times do |i|
    count += 1 if c[i] + c[i + 1] > 1_000_000
    c2.push(c[i] + c[i + 1])
  end
  c2.push(1)
  c = Marshal.load(Marshal.dump(c2))
end

p count

パスカルの三角形を応用すれば無駄な計算しなくて済みます.