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