Skip to content

Instantly share code, notes, and snippets.

@cfax
Last active March 24, 2022 15:06
Show Gist options
  • Save cfax/711d4bc0a263fd614bd561f0f94dd5c7 to your computer and use it in GitHub Desktop.
Save cfax/711d4bc0a263fd614bd561f0f94dd5c7 to your computer and use it in GitHub Desktop.
Sum all Armstrong numbers within a range
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