Skip to content

Instantly share code, notes, and snippets.

@JCGrant
Created December 3, 2015 06:21
Show Gist options
  • Save JCGrant/9e694fe0b08956343d02 to your computer and use it in GitHub Desktop.
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.
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