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