Jump to content

Primality by trial division: Difference between revisions

m
m (→‎compact version: made version 1 similar to version 2 (SAY instructions). -- ~~~~)
Line 586:
Bounded formulation has normal trial division complexity, because it can stop early through an explicit guard:
<lang haskell>primesTo m = 2 : sieve [3,5..m] where
sieve (p:xs) | p*p > m = p : xs
| True otherwise = p : sieve [x | x <- xs, rem x p /= 0]</lang>
====Postponed sieve by trial division====
To make it unbounded, the guard cannot be simply discarded, the firing up of a filter by a prime should be ''postponed'' until its ''square'' is seen amongst the candidates:
<lang haskell>primesT = 2 : 3 : sieve [5,7..] 9 (tail primesT) where
sieve (x:xs) q ps@(p:t) | x < q = x : sieve xs q ps
| True otherwise = sieve [x | x <- xs, rem x p /= 0] (head t^2) t</lang>
 
====Segmented Generate and Test====
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.