Hi,
Here are two most likely non-working non-solutions that rely on
unproven assumptions. (They work for the defined range though. :-)
Anyway, I've got a cold and will go to bed now.
------------------------ version 1
# 1089 and 2178 (= 1089 * 2) are the only 4-digit numbers that are
# reverse divisible. "Stretch" these numbers (use 10, 89 and 21, 78
as
# prefix/suffix) by keeping it reverse divisble.
#
# As Harry Kakueiki and Marcelo pointed out, this solutions misses
certain
# numbers. Shame on me.
def rdn(limit = 1_000_000)
digits = limit.to_s.size
nums = {'10' => '89', '21' => '78'}
part = ['', *(0..digits).to_a.inject([]) {|a, e|
a << ('9' * (e + 1)) << ('0' * (e + 1))
}]
part = part.sort_by {|e| e.size}
rv = {}
0.upto(digits - 5) do |d|
is = d - 4
nums.each do |prefix, suffix|
next if (prefix + suffix).to_i > limit
part.each do |p|
next if p.size < is
b = [prefix, p, suffix].join
a = b.to_i
if a < limit and !rv.has_key?(a)
b.reverse!
b = b.to_i
if b % a == 0
nums[a] = a
rv[a] = b
end
end
end
end
end
return rv
end
if __FILE__ == $0
limit = (ARGV[0] || 1_000_000).to_i
nums = rdn(limit).sort_by {|a, b| b}
nums.each do |a, b|
puts "#{b} = #{a} * #{b / a}"
end
puts "Found #{nums.size} numbers"
end
------------------------ version 2
# Assumptions:
# - The start value is 8712
# - Any number can be divided by 99 (3**2 * 11)
# - The last digit has to be 1 or 2
def rdn(limit)
rv = []
8712.step((limit || 1_000_000).to_i, 99) do |i|
r = i % 10
next if r != 1 and r != 2
j = i.to_s.reverse.to_i
d, r = i.divmod(j)
if r == 0 and d > 1
v = [j, d, i]
puts "%s * %s = %d" % v
rv << v
end
end
return rv
end
if __FILE__ == $0
limit = ARGV[0] || 1_000_000
nums = rdn(limit)
puts "Found #{nums.size} numbers"
end