Rosetta Code

Find palindromic numbers in both binary and ternary bases

Search for numbers whose binary and ternary representations are both palindromes.

Medium View source
Source rosettacode/popular/find_palindromic_numbers_in_both_binary_and_ternary_bases.vibe
# title: Find palindromic numbers in both binary and ternary bases
# source: https://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
# category: Rosetta Code
# difficulty: Medium
# summary: Search for numbers whose binary and ternary representations are both palindromes.
# tags: popular, numbers, bases, palindromes
# vibe: 0.2

def digits_in_base(number, base)
  if number == 0
    return "0"
  end

  digits = ""
  current = number

  while current > 0
    digits = ("" + (current % base)) + digits
    current = current / base
  end

  digits
end

def palindrome?(text)
  left = 0
  right = text.length - 1

  while left < right
    if text.slice(left) != text.slice(right)
      return false
    end
    left = left + 1
    right = right - 1
  end

  true
end

def first_shared_palindromes(count)
  values = []
  candidate = 1

  while values.length < count
    if palindrome?(digits_in_base(candidate, 2)) && palindrome?(digits_in_base(candidate, 3))
      values = values.push(candidate)
    end
    candidate = candidate + 1
  end

  values
end

def run
  rows = []
  rows = rows.push({
    value: 1,
    binary: digits_in_base(1, 2),
    ternary: digits_in_base(1, 3)
  })
  rows = rows.push({
    value: 6643,
    binary: digits_in_base(6643, 2),
    ternary: digits_in_base(6643, 3)
  })
  rows
end
Output
Press run to execute run from this example.
rosetta-code popular numbers bases palindromes browser-runner