primes.c revision 90828
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 const 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
44#if 0
45static char sccsid[] = "@(#)primes.c	8.5 (Berkeley) 5/10/95";
46#endif
47static const char rcsid[] =
48 "$FreeBSD: head/games/primes/primes.c 90828 2002-02-18 05:15:19Z imp $";
49#endif /* not lint */
50
51/*
52 * primes - generate a table of primes between two values
53 *
54 * By: Landon Curt Noll chongo@toad.com, ...!{sun,tolsoft}!hoptoad!chongo
55 *
56 * chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
57 *
58 * usage:
59 *	primes [start [stop]]
60 *
61 *	Print primes >= start and < stop.  If stop is omitted,
62 *	the value 4294967295 (2^32-1) is assumed.  If start is
63 *	omitted, start is read from standard input.
64 *
65 * validation check: there are 664579 primes between 0 and 10^7
66 */
67
68#include <ctype.h>
69#include <err.h>
70#include <errno.h>
71#include <limits.h>
72#include <math.h>
73#include <memory.h>
74#include <stdio.h>
75#include <stdlib.h>
76#include <unistd.h>
77
78#include "primes.h"
79
80/*
81 * Eratosthenes sieve table
82 *
83 * We only sieve the odd numbers.  The base of our sieve windows are always
84 * odd.  If the base of table is 1, table[i] represents 2*i-1.  After the
85 * sieve, table[i] == 1 if and only if 2*i-1 is prime.
86 *
87 * We make TABSIZE large to reduce the overhead of inner loop setup.
88 */
89char table[TABSIZE];	 /* Eratosthenes sieve of odd numbers */
90
91/*
92 * prime[i] is the (i-1)th prime.
93 *
94 * We are able to sieve 2^32-1 because this byte table yields all primes
95 * up to 65537 and 65537^2 > 2^32-1.
96 */
97extern ubig prime[];
98extern ubig *pr_limit;		/* largest prime in the prime array */
99
100/*
101 * To avoid excessive sieves for small factors, we use the table below to
102 * setup our sieve blocks.  Each element represents a odd number starting
103 * with 1.  All non-zero elements are factors of 3, 5, 7, 11 and 13.
104 */
105extern char pattern[];
106extern int pattern_size;	/* length of pattern array */
107
108int	hflag;
109
110void	primes(ubig, ubig);
111ubig	read_num_buf(void);
112void	usage(void);
113
114int
115main(argc, argv)
116	int argc;
117	char *argv[];
118{
119	ubig start;		/* where to start generating */
120	ubig stop;		/* don't generate at or above this value */
121	int ch;
122	char *p;
123
124	while ((ch = getopt(argc, argv, "h")) != -1)
125		switch (ch) {
126		case 'h':
127			hflag++;
128			break;
129		case '?':
130		default:
131			usage();
132		}
133	argc -= optind;
134	argv += optind;
135
136	start = 0;
137	stop = BIG;
138
139	/*
140	 * Convert low and high args.  Strtoul(3) sets errno to
141	 * ERANGE if the number is too large, but, if there's
142	 * a leading minus sign it returns the negation of the
143	 * result of the conversion, which we'd rather disallow.
144	 */
145	switch (argc) {
146	case 2:
147		/* Start and stop supplied on the command line. */
148		if (argv[0][0] == '-' || argv[1][0] == '-')
149			errx(1, "negative numbers aren't permitted.");
150
151		errno = 0;
152		start = strtoul(argv[0], &p, 0);
153		if (errno)
154			err(1, "%s", argv[0]);
155		if (*p != '\0')
156			errx(1, "%s: illegal numeric format.", argv[0]);
157
158		errno = 0;
159		stop = strtoul(argv[1], &p, 0);
160		if (errno)
161			err(1, "%s", argv[1]);
162		if (*p != '\0')
163			errx(1, "%s: illegal numeric format.", argv[1]);
164		break;
165	case 1:
166		/* Start on the command line. */
167		if (argv[0][0] == '-')
168			errx(1, "negative numbers aren't permitted.");
169
170		errno = 0;
171		start = strtoul(argv[0], &p, 0);
172		if (errno)
173			err(1, "%s", argv[0]);
174		if (*p != '\0')
175			errx(1, "%s: illegal numeric format.", argv[0]);
176		break;
177	case 0:
178		start = read_num_buf();
179		break;
180	default:
181		usage();
182	}
183
184	if (start > stop)
185		errx(1, "start value must be less than stop value.");
186	primes(start, stop);
187	exit(0);
188}
189
190/*
191 * read_num_buf --
192 *	This routine returns a number n, where 0 <= n && n <= BIG.
193 */
194ubig
195read_num_buf()
196{
197	ubig val;
198	char *p, buf[100];		/* > max number of digits. */
199
200	for (;;) {
201		if (fgets(buf, sizeof(buf), stdin) == NULL) {
202			if (ferror(stdin))
203				err(1, "stdin");
204			exit(0);
205		}
206		for (p = buf; isblank(*p); ++p);
207		if (*p == '\n' || *p == '\0')
208			continue;
209		if (*p == '-')
210			errx(1, "negative numbers aren't permitted.");
211		errno = 0;
212		val = strtoul(buf, &p, 0);
213		if (errno)
214			err(1, "%s", buf);
215		if (*p != '\n')
216			errx(1, "%s: illegal numeric format.", buf);
217		return (val);
218	}
219}
220
221/*
222 * primes - sieve and print primes from start up to and but not including stop
223 */
224void
225primes(start, stop)
226	ubig start;	/* where to start generating */
227	ubig stop;	/* don't generate at or above this value */
228{
229	char *q;		/* sieve spot */
230	ubig factor;		/* index and factor */
231	char *tab_lim;		/* the limit to sieve on the table */
232	ubig *p;		/* prime table pointer */
233	ubig fact_lim;		/* highest prime for current block */
234
235	/*
236	 * A number of systems can not convert double values into unsigned
237	 * longs when the values are larger than the largest signed value.
238	 * We don't have this problem, so we can go all the way to BIG.
239	 */
240	if (start < 3) {
241		start = (ubig)2;
242	}
243	if (stop < 3) {
244		stop = (ubig)2;
245	}
246	if (stop <= start) {
247		return;
248	}
249
250	/*
251	 * be sure that the values are odd, or 2
252	 */
253	if (start != 2 && (start&0x1) == 0) {
254		++start;
255	}
256	if (stop != 2 && (stop&0x1) == 0) {
257		++stop;
258	}
259
260	/*
261	 * quick list of primes <= pr_limit
262	 */
263	if (start <= *pr_limit) {
264		/* skip primes up to the start value */
265		for (p = &prime[0], factor = prime[0];
266		    factor < stop && p <= pr_limit; factor = *(++p)) {
267			if (factor >= start) {
268				printf(hflag ? "0x%lx\n" : "%lu\n", factor);
269			}
270		}
271		/* return early if we are done */
272		if (p <= pr_limit) {
273			return;
274		}
275		start = *pr_limit+2;
276	}
277
278	/*
279	 * we shall sieve a bytemap window, note primes and move the window
280	 * upward until we pass the stop point
281	 */
282	while (start < stop) {
283		/*
284		 * factor out 3, 5, 7, 11 and 13
285		 */
286		/* initial pattern copy */
287		factor = (start%(2*3*5*7*11*13))/2; /* starting copy spot */
288		memcpy(table, &pattern[factor], pattern_size-factor);
289		/* main block pattern copies */
290		for (fact_lim=pattern_size-factor;
291		    fact_lim+pattern_size<=TABSIZE; fact_lim+=pattern_size) {
292			memcpy(&table[fact_lim], pattern, pattern_size);
293		}
294		/* final block pattern copy */
295		memcpy(&table[fact_lim], pattern, TABSIZE-fact_lim);
296
297		/*
298		 * sieve for primes 17 and higher
299		 */
300		/* note highest useful factor and sieve spot */
301		if (stop-start > TABSIZE+TABSIZE) {
302			tab_lim = &table[TABSIZE]; /* sieve it all */
303			fact_lim = (int)sqrt(
304					(double)(start)+TABSIZE+TABSIZE+1.0);
305		} else {
306			tab_lim = &table[(stop-start)/2]; /* partial sieve */
307			fact_lim = (int)sqrt((double)(stop)+1.0);
308		}
309		/* sieve for factors >= 17 */
310		factor = 17;	/* 17 is first prime to use */
311		p = &prime[7];	/* 19 is next prime, pi(19)=7 */
312		do {
313			/* determine the factor's initial sieve point */
314			q = (char *)(start%factor); /* temp storage for mod */
315			if ((long)q & 0x1) {
316				q = &table[(factor-(long)q)/2];
317			} else {
318				q = &table[q ? factor-((long)q/2) : 0];
319			}
320			/* sive for our current factor */
321			for ( ; q < tab_lim; q += factor) {
322				*q = '\0'; /* sieve out a spot */
323			}
324		} while ((factor=(ubig)(*(p++))) <= fact_lim);
325
326		/*
327		 * print generated primes
328		 */
329		for (q = table; q < tab_lim; ++q, start+=2) {
330			if (*q) {
331				printf(hflag ? "0x%lx\n" : "%lu\n", start);
332			}
333		}
334	}
335}
336
337void
338usage()
339{
340	(void)fprintf(stderr, "usage: primes [-h] [start [stop]]\n");
341	exit(1);
342}
343