Skip to content

Instantly share code, notes, and snippets.

@t0yv0
Created March 11, 2011 00:02
Show Gist options
  • Select an option

  • Save t0yv0/865221 to your computer and use it in GitHub Desktop.

Select an option

Save t0yv0/865221 to your computer and use it in GitHub Desktop.
import Data.List
primes :: [Int]
primes = 2 : 3 : 5 : filter isPrime [7, 9 ..]
suspects :: Int -> [Int]
suspects n = takeWhile (\x -> x * x <= n) primes
isPrime :: Int -> Bool
isPrime n = all (\x -> n `mod` x /= 0) (suspects n)
factorize :: Int -> [(Int, Int)]
factorize n = f [x | x <- suspects n, n `mod` x == 0] where
f [] = [(n, 1)]
f (x:xs) = (x, r) : factorize m where
(r, m) = n `factorBy` x
factorBy :: Int -> Int -> (Int, Int)
factorBy a b = fp 0 a where
fp x a | r == 0 = fp (x + 1) q
| otherwise = (x, a)
where (q, r) = a `divMod` b
divisors :: Int -> Int
divisors n = product [x + 1 | (_, x) <- factorize n]
triangles :: [Int]
triangles = scanl1 (+) [1..]
answer = find ok triangles where
ok x = divisors x > 500
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment