Skip to content

Instantly share code, notes, and snippets.

@khigia
Created April 13, 2011 16:34
Show Gist options
  • Save khigia/917881 to your computer and use it in GitHub Desktop.
Save khigia/917881 to your computer and use it in GitHub Desktop.
Given a number, find notation bases for which number is palindrome
-- e.g. Find bases for which bday is palindre: findPal YYYYMMDD [2..1000]
-- or compile and run: echo YYYYMMDD | bdaypalbase
findPal bases n =
filter (Nothing /=) [isPal n b | b <- bases]
isPal n b =
if pal then Just (n, b, digits) else Nothing
where
digits = toDigits n b
(h1, h2) = toHalves digits
pal = h1 == (reverse h2)
toDigits n base =
let toBase_ n b l | n < b = n:l
toBase_ n b l = let (q,r) = n `quotRem` b
in toBase_ q b (r:l)
in toBase_ n base []
toHalves l@(_:_:cs) =
(h1, stripcenter h2)
where
(mid, odd) = (length l) `quotRem` 2
stripcenter = if odd == 1 then tail else id
(h1, h2) = splitAt mid l
main =
interact (show . map ((\i -> findPal [2..i] i) . read) . lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment