Skip to content

Instantly share code, notes, and snippets.

@AHaliq
Created April 29, 2022 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AHaliq/5a2f7303e620c087f7a8eb632a1b760b to your computer and use it in GitHub Desktop.
Save AHaliq/5a2f7303e620c087f7a8eb632a1b760b to your computer and use it in GitHub Desktop.
Kaprekar's constant
import Data.List
toDigits x
| x > 9 = x `mod` 10 : toDigits (x `div` 10)
| otherwise = [x]
sumFold xs = foldl (\a x -> a*10 + x) 0 xs
kaprekar :: Int -> Int -> Int
kaprekar x n = let
digs = sort $ toDigits x
v = sumFold (reverse digs) - sumFold digs
in
if v == 6174 then n else kaprekar v (n+1)
main = putStrLn $ show (kaprekar 9715 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment