I'm learning haskell by going through learnyouahaskell, doing the haskellwiki's 99 problems, and project euler problems as well. I spent most of the day yesterday working on PE problem 3, with no success as all of my solutions would run for long periods of time and bog my computer down. I read through the haskell wiki page on prime numbers but still no success, so I gave up and looked at the solution posted here.
Here is the code:
primes = 2 : filter ((==1) . length . primeFactors) [3,5..]
primeFactors n = factor n primes
where
factor n (p:ps)
| p*p > n = [n]
| n `mod` p == 0 = p : factor (n `div` p) (p:ps)
| otherwise = factor n ps
Its fast, it spits out the answer immediately, but I can't wrap my mind around this code. Specifically the primes
function and what is happening with the filter, and how this works with primes
calling primeFactors
and primeFactors
calling primes
. If I run primes
in GHCI it creates an infinite list of prime numbers and I can't figure out why.