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