primes.c revision 38153
1/*
2 * Copyright (c) 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Landon Curt Noll.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38static char copyright[] =
39"@(#) Copyright (c) 1989, 1993\n\
40	The Regents of the University of California.  All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
44static char sccsid[] = "@(#)primes.c	8.5 (Berkeley) 5/10/95";
45#endif /* not lint */
46
47/*
48 * primes - generate a table of primes between two values
49 *
50 * By: Landon Curt Noll chongo@toad.com, ...!{sun,tolsoft}!hoptoad!chongo
51 *
52 * chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
53 *
54 * usage:
55 *	primes [start [stop]]
56 *
57 *	Print primes >= start and < stop.  If stop is omitted,
58 *	the value 4294967295 (2^32-1) is assumed.  If start is
59 *	omitted, start is read from standard input.
60 *
61 * validation check: there are 664579 primes between 0 and 10^7
62 */
63
64#include <ctype.h>
65#include <err.h>
66#include <errno.h>
67#include <limits.h>
68#include <math.h>
69#include <memory.h>
70#include <stdio.h>
71#include <stdlib.h>
72#include <unistd.h>
73
74#include "primes.h"
75
76/*
77 * Eratosthenes sieve table
78 *
79 * We only sieve the odd numbers.  The base of our sieve windows are always
80 * odd.  If the base of table is 1, table[i] represents 2*i-1.  After the
81 * sieve, table[i] == 1 if and only iff 2*i-1 is prime.
82 *
83 * We make TABSIZE large to reduce the overhead of inner loop setup.
84 */
85char table[TABSIZE];	 /* Eratosthenes sieve of odd numbers */
86
87/*
88 * prime[i] is the (i-1)th prime.
89 *
90 * We are able to sieve 2^32-1 because this byte table yields all primes
91 * up to 65537 and 65537^2 > 2^32-1.
92 */
93extern ubig prime[];
94extern ubig *pr_limit;		/* largest prime in the prime array */
95
96/*
97 * To avoid excessive sieves for small factors, we use the table below to
98 * setup our sieve blocks.  Each element represents a odd number starting
99 * with 1.  All non-zero elements are factors of 3, 5, 7, 11 and 13.
100 */
101extern char pattern[];
102extern int pattern_size;	/* length of pattern array */
103
104void	primes __P((ubig, ubig, int));
105ubig	read_num_buf __P((int));
106void	usage __P((void));
107
108int
109main(argc, argv)
110	int argc;
111	char *argv[];
112{
113	ubig start;		/* where to start generating */
114	ubig stop;		/* don't generate at or above this value */
115	int ch;
116	char *p;
117	int hexa = 0;
118
119	while ((ch = getopt(argc, argv, "h")) != EOF)
120		switch (ch) {
121		case 'h':
122			hexa = 1;
123			break;
124		case '?':
125		default:
126			usage();
127		}
128	argc -= optind;
129	argv += optind;
130
131	start = 0;
132	stop = BIG;
133
134	/*
135	 * Convert low and high args.  Strtoul(3) sets errno to
136	 * ERANGE if the number is too large, but, if there's
137	 * a leading minus sign it returns the negation of the
138	 * result of the conversion, which we'd rather disallow.
139	 */
140	switch (argc) {
141	case 2:
142		/* Start and stop supplied on the command line. */
143		if (argv[0][0] == '-' || argv[1][0] == '-')
144			errx(1, "negative numbers aren't permitted.");
145
146		errno = 0;
147		start = strtoul(argv[0], &p, 0);
148		if (errno)
149			err(1, "%s", argv[0]);
150		if (*p != '\0')
151			errx(1, "%s: illegal numeric format.", argv[0]);
152
153		errno = 0;
154		stop = strtoul(argv[1], &p, 0);
155		if (errno)
156			err(1, "%s", argv[1]);
157		if (*p != '\0')
158			errx(1, "%s: illegal numeric format.", argv[1]);
159		break;
160	case 1:
161		/* Start on the command line. */
162		if (argv[0][0] == '-')
163			errx(1, "negative numbers aren't permitted.");
164
165		errno = 0;
166		start = strtoul(argv[0], &p, 0);
167		if (errno)
168			err(1, "%s", argv[0]);
169		if (*p != '\0')
170			errx(1, "%s: illegal numeric format.", argv[0]);
171		break;
172	case 0:
173		start = read_num_buf(hexa);
174		break;
175	default:
176		usage();
177	}
178
179	if (start > stop)
180		errx(1, "start value must be less than stop value.");
181	primes(start, stop, hexa);
182	exit(0);
183}
184
185/*
186 * read_num_buf --
187 *	This routine returns a number n, where 0 <= n && n <= BIG.
188 */
189ubig
190read_num_buf(int hexa)
191{
192	ubig val;
193	char *p, buf[100];		/* > max number of digits. */
194
195	for (;;) {
196		if (fgets(buf, sizeof(buf), stdin) == NULL) {
197			if (ferror(stdin))
198				err(1, "stdin");
199			exit(0);
200		}
201		for (p = buf; isblank(*p); ++p);
202		if (*p == '\n' || *p == '\0')
203			continue;
204		if (*p == '-')
205			errx(1, "negative numbers aren't permitted.");
206		errno = 0;
207		val = strtoul(buf, &p, 0);
208		if (errno)
209			err(1, "%s", buf);
210		if (*p != '\n')
211			errx(1, "%s: illegal numeric format.", buf);
212		return (val);
213	}
214}
215
216/*
217 * primes - sieve and print primes from start up to and but not including stop
218 */
219void
220primes(start, stop, hexa)
221	ubig start;	/* where to start generating */
222	ubig stop;	/* don't generate at or above this value */
223	int hexa;
224{
225	register char *q;		/* sieve spot */
226	register ubig factor;		/* index and factor */
227	register char *tab_lim;		/* the limit to sieve on the table */
228	register ubig *p;		/* prime table pointer */
229	register ubig fact_lim;		/* highest prime for current block */
230
231	/*
232	 * A number of systems can not convert double values into unsigned
233	 * longs when the values are larger than the largest signed value.
234	 * We don't have this problem, so we can go all the way to BIG.
235	 */
236	if (start < 3) {
237		start = (ubig)2;
238	}
239	if (stop < 3) {
240		stop = (ubig)2;
241	}
242	if (stop <= start) {
243		return;
244	}
245
246	/*
247	 * be sure that the values are odd, or 2
248	 */
249	if (start != 2 && (start&0x1) == 0) {
250		++start;
251	}
252	if (stop != 2 && (stop&0x1) == 0) {
253		++stop;
254	}
255
256	/*
257	 * quick list of primes <= pr_limit
258	 */
259	if (start <= *pr_limit) {
260		/* skip primes up to the start value */
261		for (p = &prime[0], factor = prime[0];
262		    factor < stop && p <= pr_limit; factor = *(++p)) {
263			if (factor >= start) {
264				printf(hexa ? "0x%x\n" : "%u\n", factor);
265			}
266		}
267		/* return early if we are done */
268		if (p <= pr_limit) {
269			return;
270		}
271		start = *pr_limit+2;
272	}
273
274	/*
275	 * we shall sieve a bytemap window, note primes and move the window
276	 * upward until we pass the stop point
277	 */
278	while (start < stop) {
279		/*
280		 * factor out 3, 5, 7, 11 and 13
281		 */
282		/* initial pattern copy */
283		factor = (start%(2*3*5*7*11*13))/2; /* starting copy spot */
284		memcpy(table, &pattern[factor], pattern_size-factor);
285		/* main block pattern copies */
286		for (fact_lim=pattern_size-factor;
287		    fact_lim+pattern_size<=TABSIZE; fact_lim+=pattern_size) {
288			memcpy(&table[fact_lim], pattern, pattern_size);
289		}
290		/* final block pattern copy */
291		memcpy(&table[fact_lim], pattern, TABSIZE-fact_lim);
292
293		/*
294		 * sieve for primes 17 and higher
295		 */
296		/* note highest useful factor and sieve spot */
297		if (stop-start > TABSIZE+TABSIZE) {
298			tab_lim = &table[TABSIZE]; /* sieve it all */
299			fact_lim = (int)sqrt(
300					(double)(start)+TABSIZE+TABSIZE+1.0);
301		} else {
302			tab_lim = &table[(stop-start)/2]; /* partial sieve */
303			fact_lim = (int)sqrt((double)(stop)+1.0);
304		}
305		/* sieve for factors >= 17 */
306		factor = 17;	/* 17 is first prime to use */
307		p = &prime[7];	/* 19 is next prime, pi(19)=7 */
308		do {
309			/* determine the factor's initial sieve point */
310			q = (char *)(start%factor); /* temp storage for mod */
311			if ((long)q & 0x1) {
312				q = &table[(factor-(long)q)/2];
313			} else {
314				q = &table[q ? factor-((long)q/2) : 0];
315			}
316			/* sive for our current factor */
317			for ( ; q < tab_lim; q += factor) {
318				*q = '\0'; /* sieve out a spot */
319			}
320		} while ((factor=(ubig)(*(p++))) <= fact_lim);
321
322		/*
323		 * print generated primes
324		 */
325		for (q = table; q < tab_lim; ++q, start+=2) {
326			if (*q) {
327				printf(hexa ? "0x%x\n" : "%u\n", start);
328			}
329		}
330	}
331}
332
333void
334usage()
335{
336	(void)fprintf(stderr, "usage: primes [start [stop]]\n");
337	exit(1);
338}
339