Skip to content

Instantly share code, notes, and snippets.

@Wollw
Last active December 12, 2015 03:09
Show Gist options
  • Save Wollw/4704721 to your computer and use it in GitHub Desktop.
Save Wollw/4704721 to your computer and use it in GitHub Desktop.
Project Euler problem 37 in Haskell
-- Project Euler Problem 37
-- The number 3797 has an interesting property. Being prime itself, it is
-- possible to continuously remove digits from left to right, and remain prime
-- at each stage: 3797, 797, 97, and 7. Similarly we can work from right to
-- left: 3797, 379, 37, and 3.
--
-- Find the sum of the only eleven primes that are both truncatable from left
-- to right and right to left.
--
-- NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
import Math.NumberTheory.Primes
import Data.List
truncations :: Integer -> [Integer]
truncations = map read . truncations_
where
truncations_ x = filter (\s -> (not . null $ s) && (show x /= s))
$ union (inits . show $ x) (tails . show $ x)
isTruncatablePrime :: Integer -> Bool
isTruncatablePrime x = case truncations x of
[] -> False
xs -> all isPrime xs
truncatablePrimes :: [Integer]
truncatablePrimes = take 11 . filter isTruncatablePrime $ primes
main = print . sum $ truncatablePrimes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment