performance - My Haskell Solution to Euler #3 is Inefficient -
i attempting solve euler problem 3 in haskell, involves finding largest prime factor of number. code runs long time , seems hang. causing code grossly inefficient?
primes = sieve (2:[3,5..]) sieve (x:xs) = x:[y | y <- (sieve xs), mod y x /= 0] sieve [] = [] primefactors n = filter (\x -> mod n x == 0) (primesunder n) primesunder z = reverse (takewhile (< z) primes) solve3 = head (primefactors 600851475143)
your main problem you're checking enormous primes -- way 600851475143
. can improve things lot observing 2 things:
- every time find prime, can decrease maximum prime @ dividing away factor.
- you have primes until reach square root of target. if primes bigger that, , know there no smaller factors, you're done.
using these 2 improvements together, without nicety used of checking primes divisibility, makes program run in snap:
factor = go (2:[3,5..]) go (p:ps) n | p*p > n = [n] | n `mod` p == 0 = p : go (p:ps) (n `div` p) | otherwise = go ps n main = print . last . factor $ 600851475143
in ghci:
*main> main 6857 (0.00 secs, 0 bytes)
you can see had inspect numbers 6857
-- 8 orders of magnitude smaller have approach.
independently, sieve dog slow. have at wiki ideas how find primes quickly.
Comments
Post a Comment