package main
import (
"fmt"
"strings"
)
// Function to check if a number is a palindrome in a given base
func isPalindrome(num, base int) bool {
if base < 2 {
return false // Invalid base
}
var strnumReversed strings.Builder
temp := num
// Convert number to string in given base
for {
digit := temp % base
if digit < 10 {
strnumReversed.WriteByte(byte('0' + digit))
} else {
strnumReversed.WriteByte(byte('A' + (digit - 10)))
}
temp /= base
if temp == 0 {
break
}
}
// Check palindrome
str := strnumReversed.String()
return str == reverseString(str)
}
// Helper function to reverse a string
func reverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes) - 1; i < j; i, j = i + 1, j - 1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func main() {
limit := 1000
fmt.Println("Numbers that are palindromes in both base 10 and base 2:")
for i := 1; i <= limit; i++ {
if isPalindrome(i, 10) && isPalindrome(i, 2) {
fmt.Printf("%d (binary: ", i)
// Print binary representation
var binary strings.Builder
temp := i
for {
if temp % 2 == 1 {
binary.WriteByte('1')
} else {
binary.WriteByte('0')
}
temp /= 2
if temp == 0 {
break
}
}
binaryStr := reverseString(binary.String())
fmt.Printf("%s)\n", binaryStr)
}
}
}
/*
run:
Numbers that are palindromes in both base 10 and base 2:
1 (binary: 1)
3 (binary: 11)
5 (binary: 101)
7 (binary: 111)
9 (binary: 1001)
33 (binary: 100001)
99 (binary: 1100011)
313 (binary: 100111001)
585 (binary: 1001001001)
717 (binary: 1011001101)
*/