loading...

re: Daily Challenge #130 - GCD Sum VIEW POST

FULL DISCUSSION
 

Haskell.

A bit ineffective because it generates all possible solutions instead of stopping when it finds the first solution.

solve :: Int -> Int -> Maybe (Int, Int)
solve sum target
  | solutions == [] = Nothing
  | otherwise       = Just (head solutions)
  where
    solutions = [(a, b) | a <- [1..(sum `div` 2)],
                          let b = sum - a,
                          gcd a b == target ]
 

Correct me if I'm wrong, but it doesn't generate all possible solutions. Haskell is lazy, and because the function only returns the head of the list, only the head can be forced into a value. So the evaluation of the list will stop as soon as a value for the head is found, meaning it does stop when the first solution is found.

 

You might be right, I had forgotten about that tiny detail.

Update: I tried with an infinite sequence to generate the solutions and the program didn't get stuck in an infinite loop, so you are right, only the first element of the sequence is generated.

Code of Conduct Report abuse