SHARE
TWEET

Multi palndromes

a guest Mar 31st, 2018 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Main (main) where
  2.  
  3. import System.Environment (getArgs)
  4.  
  5. main :: IO ()
  6. main = do
  7.     args <- getArgs
  8.     let (d,b) = case args of
  9.                   (a1:a2:_) -> (read a1, read a2)
  10.                   (a1:_) -> (read a1, 113)
  11.                   _ -> (3, 113)
  12.     mapM_ print [(n, digitList b n, digitList (b+2) n) | n <- filter (isPalindrome (b+2)) (makePalindromes b d)]
  13.  
  14. isPalindrome :: Integer -> Integer -> Bool
  15. isPalindrome base n = (n `rem` base /= 0) && go n 0
  16.   where
  17.     go f b
  18.         | f < b     = False
  19.         | otherwise = f' == b || go f' b'
  20.          where
  21.            (f',d) = f `quotRem` base
  22.             b' = b * base + d
  23.  
  24. digitList :: Integer -> Integer -> [Integer]
  25. digitList base n = go n []
  26.  where
  27.    go 0 xs = xs
  28.    go k xs = case k `quotRem` base of
  29.                (q,r) -> go q (r:xs)
  30.  
  31. revert :: Integer -> Integer -> Integer
  32. revert base n = go n 0
  33.  where
  34.    go 0 r = r
  35.    go m r = case m `quotRem` base of
  36.               (q,d) -> go q (r * base + d)
  37.  
  38. makePalindromes :: Integer -> Int -> [Integer]
  39. makePalindromes base d = do
  40.    let low = base^(d-1)
  41.        high = low * base
  42.    n <- [low .. high-1]
  43.    let b = revert base n
  44.    m <- [0 .. base-1]
  45.    return ((n * base + m)*high + b)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top