Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Created August 20, 2012 05:51
Show Gist options
  • Save dtchepak/3401408 to your computer and use it in GitHub Desktop.
Save dtchepak/3401408 to your computer and use it in GitHub Desktop.
projeuler prob 3 hack
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
@mwotton
Copy link

mwotton commented Aug 20, 2012

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 factor

firstFactor :: 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment