Skip to content

Instantly share code, notes, and snippets.

@jnape
Created November 4, 2012 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnape/4013726 to your computer and use it in GitHub Desktop.
Save jnape/4013726 to your computer and use it in GitHub Desktop.
Solution to Project Euler #3 in Haskell
module Euler3 where
{-
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
-}
factorOf :: Int -> Int -> Bool
a `factorOf` b = rem b a == 0
factorsOf :: Int -> [Int]
factorsOf n = [x | x <- [2 .. floor $ sqrt $ fromIntegral n], x `factorOf` n]
isPrime :: Int -> Bool
isPrime n
| n < 2 = False
| n == 2 = True
| otherwise = null $ factorsOf n
prime :: [Int] -> [Int]
prime [] = []
prime (x:xs)
| isPrime x = x : prime xs
| otherwise = prime xs
lastPrimeFactorOf :: Int -> Int
lastPrimeFactorOf n = last $ prime . factorsOf $ n
main :: IO ()
main = print $ lastPrimeFactorOf 600851475143
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment