Comment detail

倍数になる13進数 (Nested Flatten)

This comment is reply for 383 shuyo: お題から少し外れるが、条件を満たす数を探...(倍数になる13進数). Go to thread root.

先のコードはバグがあって、解の見落としが発生することがわかりました。すんません。 ということで修正&最適化したものを投稿。30桁くらいまでならほぼ瞬殺で出力します。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def search(m, rem, result)
  rem2 = rem[1..rem.length-1]
  ai = -rem[0]
  min = rem2.inject(m+ai-1){|sum,a|sum+(a>0?0:a*9)}/ai
  max = rem2.inject(m){|sum,a|sum+(a>0?a*9:0)}/ai
  #puts "#{m}, #{rem.inspect}, #{min}, #{max}"
  min = 0 if min < 0
  max = 9 if max > 9
  return if min > max
  min.upto(max) do |x|
    if rem2.length == 1
      if (m-x*ai) % rem2[0] == 0
        y = (x*ai-m) / rem2[0]
        puts "#{result}#{x}#{y}" if y>=0 && y<=9
      end
    else
      search m-x*ai, rem2, "#{result}#{x}"
    end
  end
end

d=3 # keta - 1
while true
  puts "keta: #{d+1} =========================================================="
  max_n = 13**d / 10**d
  1.upto(9) do |ad| # highest digit
    x13 = ad*13**d
    x10 = ad*10**d
    min_n = (x13 + 9*(13**d-1)/12) / (x10 + (10**d-1))
    puts [min_n, max_n].join(', ') if min_n > max_n
    min_n.upto(max_n) do |n|
      m = x13 - x10*n
      rem = []
      0.upto(d-1){|i| rem.unshift 13**i - 10**i * n }
      search m, rem, "#{ad}"
    end
  end
  d+=1
end

Index

Feed

Other

Link

Pathtraq

loading...