How to resolve the algorithm Find palindromic numbers in both binary and ternary bases step by step in the Kotlin programming language

Published on 22 June 2024 08:30 PM

How to resolve the algorithm Find palindromic numbers in both binary and ternary bases step by step in the Kotlin programming language

Table of Contents

Problem Statement

It's permissible to assume the first two numbers and simply list them.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Find palindromic numbers in both binary and ternary bases step by step in the Kotlin programming language

This Kotlin program generates a sequence of numbers that are palindromic in both binary and ternary bases, up to a count of 6. A palindromic number is one that reads the same forwards and backwards, such as 101 in binary or 121 in decimal.

The program starts by defining several helper functions:

  • toTernaryString() converts a decimal number to its ternary (base 3) representation.
  • toBinaryString() wraps the Java Long.toBinaryString() method to convert a decimal number to its binary (base 2) representation.
  • isPalindromic() checks if a given string is palindromic.
  • printPalindrome() prints a number in decimal, binary, and ternary bases, and includes a blank line afterwards.

The main logic of the program is in the createPalindrome3() function, which takes a decimal number n and returns the decimal equivalent of a ternary palindrome that has n as its left part. This is done by mirroring the ternary representation of n and adding an additional '1' digit in the middle.

The main() function uses a loop to generate a sequence of potential palindromic numbers. It starts with i = 1 and increments it until it finds 6 palindromic numbers. For each i, it uses the createPalindrome3() function to create a ternary palindrome, and then checks if it is also a binary palindrome. If so, it prints the number in all three bases and increments the count.

The program outputs the first 6 numbers that are palindromic in both binary and ternary bases:

Decimal : 0
Binary  : 0
Ternary : 0

Decimal : 1
Binary  : 1
Ternary : 1

Decimal : 41
Binary  : 101001
Ternary : 10101

Decimal : 121
Binary  : 1111001
Ternary : 1111011

Decimal : 481
Binary  : 111101001
Ternary : 1210212

Decimal : 10201
Binary  : 100111000001
Ternary : 210021102

Source code in the kotlin programming language

// version 1.0.5-2

/** converts decimal 'n' to its ternary equivalent */
fun Long.toTernaryString(): String = when {
    this < 0L  -> throw IllegalArgumentException("negative numbers not allowed")
    this == 0L -> "0"
    else   -> {
        var result = ""
        var n = this
        while (n > 0) {
            result += n % 3
            n /= 3
        }
        result.reversed()
    }
}

/** wraps java.lang.Long.toBinaryString in a Kotlin extension function */
fun Long.toBinaryString(): String = java.lang.Long.toBinaryString(this)

/** check if a binary or ternary numeric string 's' is palindromic */
fun isPalindromic(s: String): Boolean = (s == s.reversed())

/** print a number which is both a binary and ternary palindrome in all three bases */
fun printPalindrome(n: Long) {
    println("Decimal : $n")
    println("Binary  : ${n.toBinaryString()}")
    println("Ternary : ${n.toTernaryString()}")
    println()
}

/** create a ternary palindrome whose left part is the ternary equivalent of 'n' and return its decimal equivalent */
fun createPalindrome3(n: Long): Long {
    val ternary = n.toTernaryString()
    var power3 = 1L
    var sum = 0L
    val length = ternary.length
    for (i in 0 until length) {  // right part of palindrome is mirror image of left part
        if (ternary[i] > '0') sum += (ternary[i].toInt() - 48) * power3
        power3 *= 3L
    }
    sum += power3 // middle digit must be 1
    power3 *= 3L
    sum += n * power3  // value of left part is simply 'n' multiplied by appropriate power of 3
    return sum
}

fun main(args: Array<String>) {
    var i = 1L
    var p3: Long
    var count = 2
    var binStr: String
    println("The first 6 numbers which are palindromic in both binary and ternary are:\n")
    // we can assume the first two palindromic numbers as per the task description
    printPalindrome(0L)  // 0 is a palindrome in all 3 bases
    printPalindrome(1L)  // 1 is a palindrome in all 3 bases

    do {
        p3 = createPalindrome3(i)
        if (p3 % 2 > 0L)  { // cannot be even as binary equivalent would end in zero
            binStr = p3.toBinaryString()
            if (binStr.length % 2 == 1) { // binary palindrome must have an odd number of digits
                if (isPalindromic(binStr)) {
                    printPalindrome(p3)
                    count++
                }
            }
        }
        i++
    }
    while (count < 6)
}


  

You may also check:How to resolve the algorithm Primality by trial division step by step in the CoffeeScript programming language
You may also check:How to resolve the algorithm Digital root step by step in the Cowgol programming language
You may also check:How to resolve the algorithm Stream merge step by step in the Nim programming language
You may also check:How to resolve the algorithm Super-Poulet numbers step by step in the C++ programming language
You may also check:How to resolve the algorithm GUI enabling/disabling of controls step by step in the NewLISP programming language