Skip to content

Instantly share code, notes, and snippets.

@fbiville
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save fbiville/aaee46d9bece0b64131c to your computer and use it in GitHub Desktop.

Select an option

Save fbiville/aaee46d9bece0b64131c to your computer and use it in GitHub Desktop.
module Euler12 (triangle,multipleCount) where
import Data.List
triangle :: Int -> Int
triangle n = head . dropWhile (\m -> multipleCount m < n) $ [ i*(i+1) `div` 2 | i <- [1..] ]
multipleCount :: Int -> Int
multipleCount number =
product $ map (+1) $ map length (group pFactors)
where pFactors = primeFactors [] number 2
primeFactors :: [Int] -> Int -> Int -> [Int]
primeFactors acc n m
| (isPrime n) = n:acc
| (rmd == 0) = primeFactors acc' n' m
| otherwise = primeFactors acc n (nextPrime m)
where rmd = n `mod` m
n' = n `div` m
acc' = m:acc
nextPrime :: Int -> Int
nextPrime 2 = 3
nextPrime n = head $ dropWhile (not . isPrime) [n+2,n+4..]
isPrime :: Int -> Bool
isPrime 2 = True
isPrime number = (number `mod` 2 /= 0)
&& (null range || not (any (\divisor -> number `mod` divisor == 0) range))
where upper = 1+truncate(sqrt(fromIntegral(number)))
range = [3,5..upper]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment