Last active
March 24, 2022 15:06
-
-
Save cfax/711d4bc0a263fd614bd561f0f94dd5c7 to your computer and use it in GitHub Desktop.
Sum all Armstrong numbers within a range
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
digits :: (Integral n) => n -> [n] | |
digits = reverse . go | |
where go n | |
| n < 10 = [n] | |
| otherwise = r : digits q | |
where (q, r) = n `quotRem` 10 | |
numberLength :: Int -> Int | |
numberLength = length . digits | |
powerNumber :: Int -> [Int] | |
powerNumber n = [d ^ exponent | d <- digits n] | |
where exponent = numberLength n | |
isArmstrong :: Int -> Bool | |
isArmstrong a = a == sum (powerNumber a) | |
sortEnds :: Int -> Int -> (Int, Int) | |
sortEnds a b = if a < b then (a, b) else (b, a) | |
sumAllArmstrongNumber :: Int -> Int -> Int | |
sumAllArmstrongNumber a b = sum [x | x <- [start..end], isArmstrong x] | |
where (start, end) = sortEnds a b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment