Created
April 29, 2022 15:37
-
-
Save AHaliq/5a2f7303e620c087f7a8eb632a1b760b to your computer and use it in GitHub Desktop.
Kaprekar's constant
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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