Created
December 3, 2015 06:21
-
-
Save JCGrant/9e694fe0b08956343d02 to your computer and use it in GitHub Desktop.
Chains of square numbers which remain squares when repeatedly adding digits. [1,16,169] appears to be the only chain with a length greater than 2.
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.Maybe | |
isSquare :: Integer -> Bool | |
isSquare x | |
= root ^ 2 == x | |
where | |
root = floor $ sqrt $ fromIntegral x | |
append :: [Integer] -> Integer -> [Integer] | |
append ys x | |
= [x*10 + i | i <- ys] | |
squares :: [Integer] -> [Integer] | |
squares = filter isSquare | |
maybeHead :: [a] -> Maybe a | |
maybeHead xs | |
| null xs = Nothing | |
| otherwise = Just (head xs) | |
nextSquare :: Integer -> Maybe Integer | |
nextSquare x | |
= maybeHead $ squares $ append [1..9] x | |
squareChain :: Integer -> [Integer] | |
squareChain x = squareChain' [x] | |
squareChain' :: [Integer] -> [Integer] | |
squareChain' xs | |
| isNothing nextSquareOfXs = xs | |
| otherwise = squareChain' (xs ++ [fromJust nextSquareOfXs]) | |
where | |
nextSquareOfXs = nextSquare (last xs) | |
squareChains :: Integer -> [[Integer]] | |
squareChains n | |
= map squareChain $ squares [1..n] | |
squareChainsOfLengthGreaterThan :: Integer -> [[Integer]] | |
squareChainsOfLengthGreaterThan n x | |
= filter (\x -> length x >= x) $ squareChains n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment