Haskell Sieve of Eratosthenes with list of composites -
i have implement classic problem of sieve of eratosthenes in haskell project. rather computing each prime have compare numbers between lists. instance pass list of potential primes (parameter 1) , list of composites (list 2). sieve [2..10] []
results list [2,3,5,7]
.
i think close , compiles, appends every item prime list rather throwing out composites. thinking take list x of numbers 2..10
or whatever , list y of composites use elem
see if head of list x found in list y , if append list z , print. in advance!
currently code returns in first list , refuses sort. sieve [2..10] []
results in [2,3,4,5,6,7,8,9,10]
sieve ::[int]->[int]->[int] z = [] sieve [] [] = [] sieve x [] = x sieve [] y = y sieve xs ys = if ((elem (head xs)) ys) (sieve (tail xs) ys) else ((head xs):z)
what call sieve
called minus
, subtracting second list first, assuming both ordered, increasing lists of numbers. enough compare 2 head elements, without elem
calls.
but still work, had provided proper definition z
. z=[]
placeholder, make compile (right?); it's not right definition. should have been:
sieve :: [int] -> [int] -> [int] -- z = [] sieve [] [] = [] sieve x [] = x sieve [] y = y sieve xs ys = if ((elem (head xs)) ys) (sieve (tail xs) z) else ((head xs) : sieve (tail xs) ys ) z = ... -- need remove (head xs) ys
for last comment's task, use e.g. delete
function.
this still won't produce list of primes without list of composites, initial call can not second list empty (or else, you'd same first argument back, do, because of sieve x [] = x
equation):
primesamong input = sieve input composites
but composites
? eratosthenes's answer is, why, multiples of primes! (and trial division says: composites have other primes divisors).
given prime, 2, count: 2,4,6,...; , 3, say, it's 3,6,9,12,...; find multiples. let's write down:
composites = mutliplesof primes mutliplesof primes = [ mult | p <- primes, mult <- [...] ]
this doesn't quite fit: multiplesof
needs argument:
primes = primesamong input primesamong input = sieve input (mutliplesof primes)
we seem chasing our own tail here; don't have primes
yet; can use instead? there harm in finding multiples of non-primes, primes?
after have running code, try find way use primes
after all.
Comments
Post a Comment