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