Created
August 20, 2012 05:51
-
-
Save dtchepak/3401408 to your computer and use it in GitHub Desktop.
projeuler prob 3 hack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Monad | |
import Data.List | |
import Data.Maybe | |
factorBy :: Int -> Int -> Maybe (Int, Int) | |
factorBy n factor = if snd result == 0 then Just (fst result, factor) | |
else Nothing | |
where result = n `divMod` factor | |
firstFactor :: Int -> Maybe (Int, Int) | |
firstFactor n = join . find isJust . map (factorBy n) $ [2..n] | |
problem3 :: Int -> Maybe Int | |
problem3 n = case firstFactor n of | |
Nothing -> Nothing | |
(Just (1,x)) -> Just x | |
(Just (x,y)) -> problem3 x | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
my version:
import Control.Monad
import Data.List
import Data.Maybe
factorBy :: Int -> Int -> Maybe (Int, Int)
factorBy n factor = guard (s==0) >> return (f, factor)
where (f,s) = n
divMod
factorfirstFactor :: Int -> Maybe (Int, Int)
firstFactor n = listToMaybe . mapMaybe (factorBy n) $ [2..n]
problem3 :: Int -> Maybe Int
problem3 n = firstFactor n >>= (a,b) ->
if a == 1
then return b
else problem3 a