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