Skip to content

Instantly share code, notes, and snippets.

@ktilcu
Last active August 15, 2017 20:34
Show Gist options
  • Select an option

  • Save ktilcu/2a71f7933946bf98a337f4b55398c116 to your computer and use it in GitHub Desktop.

Select an option

Save ktilcu/2a71f7933946bf98a337f4b55398c116 to your computer and use it in GitHub Desktop.
kyle-Programming Problem: Ace of Palindrome Base

A palindromic number is a number that remains the same when it is reversed; that is to sayit is the same forwards and backwards. For example 14,541 and 252 are both palindromeswhile 54 and 123 are not. The aforementioned cases are all in decimal but it's possible for numbers that are not palindromic in base 10 to be palindromic in other bases.

17 for example is not palindromic in decimal but is palindromic when represented in binary: 100012.Another example is 16 which is not palindromic in decimal but is palindromic in base 3: 1213.

Write a Python program determines the smallest base (greater than or equal to 2) in which the first 1000 positive decimal integers are palindromes. Please include unit tests for any function you write.

Here's example CSV output for the first 20 non-negative integers:

"decimal", "smallest base in which the number is a palindrome"
0, 2
1, 2
2, 3
3, 2
4, 3
5, 2
6, 5
7, 2
8, 3
9, 2
10, 3
11, 10
12, 5
13, 3
14, 6
15, 2
16, 3
17, 2
18, 5
19, 18
const isPalindrome = (s) => s.toString() === s.toString().split('').reverse().join('');
const a = (n, predicate) => {
var base=2;
while (!predicate(n.toString(base)) &&base < 36) {
base++;
}
return base;
}
console.log(Array(1000)
.fill('')
.map((_,i)=> [i,a(i, isPalindrome)])
.map(x=>x.join(','))
.join('\n'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment