## Sieving A Polynomial

### May 30, 2017

We begin by writing a simple function that factors integers:

(define (factors n) (let loop ((n n) (f 2) (fs (list))) (cond ((< n (* f f)) (reverse (cons n fs))) ((positive? (modulo n f)) (loop n (+ f 1) fs)) (else (loop (/ n f) f (cons f fs))))))

It doesn’t get any simpler than that. Then we can solve the problem by enumerating the numbers that are 1 modulo 4, by starting with 5 and increasing in step of 4 until we reach the limit, factoring each of them:

> (time (for-each (lambda (n) (display n) (display #\tab) (display (factors n)) (newline)) (range 5 (+ 300001 1) 4))) 5 (5) 9 (3 3) 13 (13) 17 (17) 21 (3 7) 25 (5 5) 29 (29) ... 299977 (299977) 299981 (11 27271) 299985 (3 5 7 2857) 299989 (23 13043) 299993 (299993) 299997 (3 3 3 41 271) 300001 (13 47 491) (time (for-each (lambda (...) ...) ...)) 3 collections 0.914591752s elapsed cpu time, including 0.002393507s collecting 2.947164401s elapsed real time, including 0.002407402s collecting 27820480 bytes allocated, including 29532000 bytes reclaimed

Over half the time is spent computing the factorizations; the rest is spent printing them:

> (time (length (map factors (range 5 (+ 300001 1) 4)))) (time (length (map factors ...))) 1 collection 0.497749733s elapsed cpu time, including 0.004209815s collecting 0.497980266s elapsed real time, including 0.004216131s collecting 11065296 bytes allocated, including 4766688 bytes reclaimed 75000

If you’re working with lots of primes, it is almost always better to find a way to use a sieve to make the desired calculation. (The previous sentence is true; it is even more true if you remove the word *almost*.) Here is our sieving solution, which sieves over the polynomial 4*k* + 1 for 1 ≤ *k* ≤ ⌊*n* / 4⌋:

(define (factors-1mod4 n) (let* ((len (quotient (- n 1) 4)) (factors (make-vector (+ len 1) (list)))) (define (sieve p pp) ; p = prime, pp = prime-power (let* ((k (if (= (modulo pp 4) 1) pp (* 3 pp))) (k (quotient (- k 1) 4))) (do ((i k (+ i pp))) ((< len i)) (vector-set! factors i (cons p (vector-ref factors i)))))) (do ((ps (cdr (primes (isqrt n))) (cdr ps))) ((null? ps)) (do ((pp (car ps) (* pp (car ps)))) ((< n pp)) (sieve (car ps) pp))) (do ((k 0 (+ k 1))) ((< len k) factors) (let* ((n (+ (* 4 k) 1)) (fs (vector-ref factors k)) (f (/ n (apply * fs)))) (vector-set! factors k (cond ((null? fs) (list n)) ((= f 1) (reverse fs)) (else (reverse (cons f fs)))))))))

We’ll describe that function in a moment; first, here are the timing comparisons:

> (time (let ((fs (factors-1mod4 300001))) (do ((k 1 (+ k 1))) ((= (vector-length fs) k)) (display (+ (* 4 k) 1)) (display #\tab) (display (vector-ref fs k)) (newline)))) 5 (5) 9 (3 3) 13 (13) 17 (17) 21 (3 7) 25 (5 5) 29 (29) ... 299977 (299977) 299981 (11 27271) 299985 (3 5 7 2857) 299989 (23 13043) 299993 (299993) 299997 (3 3 3 41 271) 300001 (13 47 491) (time (for-each (lambda (...) ...) ...)) 3 collections 0.914591752s elapsed cpu time, including 0.002393507s collecting 2.947164401s elapsed real time, including 0.002407402s collecting 27820480 bytes allocated, including 29532000 bytes reclaimed (time (let ((...)) ...)) 3 collections 0.375754800s elapsed cpu time, including 0.011405073s collecting 3.366967942s elapsed real time, including 0.011437653s collecting 26286032 bytes allocated, including 23110192 bytes reclaimed

Almost all of the time is spent printing; nearly no time is spent computing the factorizations:

> (time (vector-length (factors-1mod4 300001))) (time (vector-length (factors-1mod4 300001))) 1 collection 0.019011232s elapsed cpu time, including 0.002646539s collecting 0.019020886s elapsed real time, including 0.002651997s collecting 7084752 bytes allocated, including 6562944 bytes reclaimed 75001

That’s a reduction from half a second to a fiftieth of a second, which pretty clearly shows the advantage of sieving.

The key is the vector *factors* that holds ⌊*n* / 4⌋ sets of factors; the element at index *k* corresponds to the number 4*k* + 1. We can sieve over the polynomial because it is a linear sequence; when we advance to the next index, we increase the number it represents by 4, so when we are sieving on 7, say, we skip 7 vector elements representing 28 on the number line. Sieving is performed by the local function `sieve`

; the calculation of *k* in the function computes the index of the smallest multiple of *pp* that is 1 modulo 4, which is *pp* itself if *pp* is equivalent to 1 modulo 4, or 3 × *pp* if *pp* is equivalent to 3 modulo 4.

The heart of the function is the two nested `do`

loops, the outer loop on *p* and the inner loop on *pp*. Variable *p*, which is implicit in `(car ps)`

, runs over the primes from 3 to the square root of the parameter *n* (we don’t use 2 because all of the numbers of interest are odd), computed using a standard Sieve of Eratosthenes. Variable *pp* runs over the powers of the primes, so we can capture all of the factors in their multiplicity. Function `sieve`

skips *pp* vector elements at a time, marking each list that it visits with factor *p*.

The final loop on *k* cleans up the vector of factors. If an element of the vector contains the null list, then the corresponding *n* is prime. If the product of the factors is equal to *n*, then the list is complete, and needs only to be reversed so the factors appear in increasing order. If the product of the factors is less than *n*, then *n* has one additional factor greater than its square root, which must be added to the list.

For sake of completeness, here is the standard Sieve of Eratosthenes used to compute the sieving primes:

(define (primes n) ; list of primes not exceeding n (let* ((len (quotient (- n 1) 2)) (bits (make-vector len #t))) (let loop ((i 0) (p 3) (ps (list 2))) (cond ((< n (* p p)) (do ((i i (+ i 1)) (p p (+ p 2)) (ps ps (if (vector-ref bits i) (cons p ps) ps))) ((= i len) (reverse ps)))) ((vector-ref bits i) (do ((j (+ (* 2 i i) (* 6 i) 3) (+ j p))) ((<= len j) (loop (+ i 1) (+ p 2) (cons p ps))) (vector-set! bits j #f))) (else (loop (+ i 1) (+ p 2) ps))))))

You can run the program at http://ideone.com/VaC9RY.

Simple Python3 with lots of space for optimization, possibly

Output

In python:

Above solution takes 0.42 seconds for all numbers up to 75000 on my machine. Below solution uses a bigger wheel and goes for Brent algorithm trial division for larger numbers. Takes 0.08 seconds for first 75000.

Good ‘ol shell:

There’s factor in coreutils? That’s cool.

(And surely the spec includes 1.)

@Rutger: Please time the following function using the same parameters as your other timings:

@Jussi: Unix has had

`factor`

forever. It uses naive trial division.@Praxis, I never knew.

The info page for the GNU coreutils factor says it uses “the Pollard Rho algorithm” which is “particularly effective for numbers with relatively small factors” (when it’s compiled with the GNU MP library). It recommends other methods for factoring products of large primes.

@Jussi: The V7 source code is in assembler, HERE; the man page is HERE.

I’m not an assembler expert, but I see things like

that looks an awful lot like trial division (there is no division in the Pollard Rho algorithm), and something like

that looks an awful lot like trial division by odd numbers.

I also note that the man page mentions the time complexity as O(sqrt

n), which is characteristic of trial division, not Pollard Rho.I’ve always been under the impression that Unix

`factor`

used trial division. I’m not surprised that the GNU folks changed the algorithm.@Praxis, thanks. I see also an interfance change between V7 and GNU factor: V7 takes one argument (or none), GNU takes any number of arguments and reports on all of them.

To understate the effect, there’s a noticable difference between the running times of these (on a Red Hat server with recent coreutils, but the point should be robust):

@programmingpraxis: tried timing your reply, but it uses an undefined primes() function.

@Rutger: Sorry. I added

`primes`

and`prod`

, both of which are called by the function.Had a little more modifications to the code, but here is the result: 0.0156 seconds.

@Rutger: So to process

n= 75,000, it’s 0.42 seconds for trial division by 2 and odds, a five-times improvement to 0.08 seconds for a 2,3,5,7-wheel (sincen= 75,000 you never call Brent-rho), and another five-times improvement to 0.0156 for sieving. And sieving has a slower order of growth than the other two, O(lognlog logn) compared to O(sqrtn). Sieving always wins!Thank you for doing the timing comparison.

May 30th, 2017.c:May 30th, 2017.out:On an Apple Power Mac G4 (AGP Graphics) (450MHz processor, 1GB memory) to run the solution took:

approximately forty-six seconds on Mac OS 9.2.2 (International English) (the solution interpreted using Leonardo IDE 3.4.1);

approximately one second on Mac OS X 10.4.11 (the solution compiled using Xcode 2.2.1).

(I’m just trying to solve the problems posed by this ‘site whilst I try to get a job; I’m well aware that my solutions are far from the best – but, in my defence, I don’t have any traditional qualifications in computer science :/ )