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

mu chance or much chance ?

日々の戯れ言

Project Euler 43

Project Euler

Problem43を解きました.

  • Sub-string divisibility

The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.

Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:

d2d3d4=406 is divisible by 2
d3d4d5=063 is divisible by 3
d4d5d6=635 is divisible by 5
d5d6d7=357 is divisible by 7
d6d7d8=572 is divisible by 11
d7d8d9=728 is divisible by 13
d8d9d10=289 is divisible by 17
Find the sum of all 0 to 9 pandigital numbers with this property.

https://projecteuler.net/problem=43

問題は「0から9のパンデジタル数の中で,d2d3d4が2で割り切れ,d3d4d5が3で割り切れ,d4d5d6が5で割り切れ,d5d6d7が7で割り切れ,d6d7d8が11で割り切れ,d7d8d9が13で割り切れ,d8d9d10が17で割り切れる数の総和を求めよ.ただし,dnは上位n桁目の数とする」.

n = Array 0..9

num = n.permutation.to_a
sum = 0

num.length.times do |i|
  # d2d3d4
  k = num[i].join[1].to_i * 100 + num[i].join[2].to_i * 10 + num[i].join[3].to_i
  next if k.odd?
  # d3d4d5
  k = num[i].join[2].to_i * 100 + num[i].join[3].to_i * 10 + num[i].join[4].to_i
  next if (k % 3).nonzero?
  # d4d5d6
  k = num[i].join[3].to_i * 100 + num[i].join[4].to_i * 10 + num[i].join[5].to_i
  next if (k % 5).nonzero?
  # d5d6d7
  k = num[i].join[4].to_i * 100 + num[i].join[5].to_i * 10 + num[i].join[6].to_i
  next if (k % 7).nonzero?
  # d6d7d8
  k = num[i].join[5].to_i * 100 + num[i].join[6].to_i * 10 + num[i].join[7].to_i
  next if (k % 11).nonzero?
  # d7d8d9
  k = num[i].join[6].to_i * 100 + num[i].join[7].to_i * 10 + num[i].join[8].to_i
  next if (k % 13).nonzero?
  # d8d9d10
  k = num[i].join[7].to_i * 100 + num[i].join[8].to_i * 10 + num[i].join[9].to_i
  next if (k % 17).nonzero?
  sum += num[i].join.to_i
end

p sum

permutationと力技で解きました.