Rosetta Code

Palindromic gapful numbers

Find the first palindromic gapful numbers in a bounded decimal range.

Medium View source
Source rosettacode/popular/palindromic_gapful_numbers.vibe
# title: Palindromic gapful numbers
# source: https://rosettacode.org/wiki/Palindromic_gapful_numbers
# category: Rosetta Code
# difficulty: Medium
# summary: Find the first palindromic gapful numbers in a bounded decimal range.
# tags: popular, numbers, search, divisibility
# vibe: 0.4

def palindromic_gapful?(number)
  text = number.to_s
  if text.length < 3
    return false
  end

  if text != text.reverse
    return false
  end

  digits = text.chars
  divisor = (digits.first.to_i * 10) + digits.last.to_i
  number % divisor == 0
end

def first_palindromic_gapful_numbers(count)
  values = []

  outer = 1
  while outer <= 9 && values.length < count
    middle = 0
    while middle <= 9 && values.length < count
      candidate = (outer * 100) + (middle * 10) + outer
      if palindromic_gapful?(candidate)
        values << candidate
      end
      middle = middle + 1
    end
    outer = outer + 1
  end

  outer = 1
  while values.length < count
    inner = 0
    while inner < 100 && values.length < count
      tens = inner / 10
      ones = inner % 10
      candidate = (outer * 1000) + (tens * 100) + (ones * 10) + outer
      if palindromic_gapful?(candidate)
        values << candidate
      end
      inner = inner + 1
    end
    outer = outer + 1
  end

  values
end

def run
  first_palindromic_gapful_numbers(10)
end
Output
Press run to execute run from this example.