FYI: final version posted to Rosetta Code.
struct PalindromicGapfuls
include Enumerable(UInt64)
@nn : Int32
def initialize(@digit : Int32)
@nn = @digit * 11 # digit gapful divisor
end
def each
(2..).each do |power|
base = 10_u64 ** (power >> 1) # value of middle digit position
this_lo = base * @digit # starting half for this digit: 10.. to 90..
next_lo = base * (@digit + 1) # starting half for next digit: 20.. to 100..
this_lo.step(to: next_lo - 1, by: 10) do |front_half| # d_10; d_20; d_30; ...
if power.odd? # for even number of total digits: ab..ba
front_half.upto(front_half + 9) do |upper_half| # d_n0 to d_n9
palindrome_half = upper_half.to_s
palindrome = (palindrome_half + palindrome_half.reverse).to_u64
yield palindrome if palindrome % @nn == 0
end
else # for odd number of total digits: ab..m..ba
palindrome_half = (front_half // 10).to_s
palindrome = (palindrome_half + "0" + palindrome_half.reverse).to_u64
# increase palindome middle digit from ---0--- to ---9---
10.times do
yield palindrome if palindrome % @nn == 0
palindrome += base
end
end
end
end
end
end
count, keep = 20, 20
puts "First 20 palindromic gapful numbers ending with:"
1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).first(count).last(keep)}" }
count, keep = 100, 15
puts "\nLast 15 of first 100 palindromic gapful numbers ending in:"
1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).first(count).last(keep)}" }
count, keep = 1_000, 10
puts "\nLast 10 of first 1000 palindromic gapful numbers ending in:"
1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).first(count).last(keep)}" }
count, keep = 100_000, 1
puts "\n100,000th palindromic gapful number ending with:"
1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).first(count).last(keep)}" }
count, keep = 1_000_000, 1
puts "\n1,000,000th palindromic gapful number ending with:"
1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).first(count).last(keep)}" }
count, keep = 10_000_000, 1
puts "\n10,000,000th palindromic gapful number ending with:"
1.upto(9) { |digit| puts "#{digit} : #{PalindromicGapfuls.new(digit).first(count).last(keep)}" }