Search code examples
haskellprimesgoldbach-conjecture

Implement Goldbach's conjecture in Haskell


So Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers. I am trying to write a Haskell program that will, given a positive even integer, find those 2 prime numbers:

goldbach n = head [(x,y) | x <- primesR 2 (n-1),
                           let y = n-x-1, isPrime y]

Where primesR is given below as (returns primes in range):

primesR :: Integral a => a -> a -> [a]
primesR a b = takeWhile (<= b) $ dropWhile (< a) $ sieve [2..]
  where sieve (n:ns) = n:sieve [ m | m <- ns, m `mod` n /= 0 ]

However, this doesn't consistently give me the correct prime numbers. I think my indexing is off but I'm not sure how/where?


Solution

  • turns out the problem is a small logical mistake:

    goldbach n = head [(x,y) | x <- primesR 2 (n-1),
                               let y = n-x, isPrime y]
    

    as n is supposed to be x+y it should be let y=n-x instead