xref: /freebsd/usr.bin/primes/primes.c (revision 63d1fd5970ec814904aa0f4580b10a0d302d08b2)
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 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1989, 1993\n\
36 	The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38 
39 #ifndef lint
40 #if 0
41 static char sccsid[] = "@(#)primes.c	8.5 (Berkeley) 5/10/95";
42 #endif
43 static const char rcsid[] =
44  "$FreeBSD$";
45 #endif /* not lint */
46 
47 /*
48  * primes - generate a table of primes between two values
49  *
50  * By: Landon Curt Noll chongo@toad.com, ...!{sun,tolsoft}!hoptoad!chongo
51  *
52  * chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
53  *
54  * usage:
55  *	primes [-h] [start [stop]]
56  *
57  *	Print primes >= start and < stop.  If stop is omitted,
58  *	the value 4294967295 (2^32-1) is assumed.  If start is
59  *	omitted, start is read from standard input.
60  *
61  * validation check: there are 664579 primes between 0 and 10^7
62  */
63 
64 #include <sys/capsicum.h>
65 #include <ctype.h>
66 #include <err.h>
67 #include <errno.h>
68 #include <inttypes.h>
69 #include <limits.h>
70 #include <math.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <nl_types.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	hflag;
91 
92 static void	primes(ubig, ubig);
93 static ubig	read_num_buf(void);
94 static void	usage(void);
95 
96 int
97 main(int argc, char *argv[])
98 {
99 	ubig start;		/* where to start generating */
100 	ubig stop;		/* don't generate at or above this value */
101 	int ch;
102 	char *p;
103 
104 	/* Cache NLS data, for strerror, for err(3), before cap_enter. */
105 	(void)catopen("libc", NL_CAT_LOCALE);
106 
107 	if (cap_enter() < 0 && errno != ENOSYS)
108 		err(1, "cap_enter");
109 
110 	while ((ch = getopt(argc, argv, "h")) != -1)
111 		switch (ch) {
112 		case 'h':
113 			hflag++;
114 			break;
115 		case '?':
116 		default:
117 			usage();
118 		}
119 	argc -= optind;
120 	argv += optind;
121 
122 	start = 0;
123 	stop = SPSPMAX;
124 
125 	/*
126 	 * Convert low and high args.  Strtoumax(3) sets errno to
127 	 * ERANGE if the number is too large, but, if there's
128 	 * a leading minus sign it returns the negation of the
129 	 * result of the conversion, which we'd rather disallow.
130 	 */
131 	switch (argc) {
132 	case 2:
133 		/* Start and stop supplied on the command line. */
134 		if (argv[0][0] == '-' || argv[1][0] == '-')
135 			errx(1, "negative numbers aren't permitted.");
136 
137 		errno = 0;
138 		start = strtoumax(argv[0], &p, 0);
139 		if (errno)
140 			err(1, "%s", argv[0]);
141 		if (*p != '\0')
142 			errx(1, "%s: illegal numeric format.", argv[0]);
143 
144 		errno = 0;
145 		stop = strtoumax(argv[1], &p, 0);
146 		if (errno)
147 			err(1, "%s", argv[1]);
148 		if (*p != '\0')
149 			errx(1, "%s: illegal numeric format.", argv[1]);
150 		if (stop > SPSPMAX)
151 			errx(1, "%s: stop value too large.", argv[1]);
152 		break;
153 	case 1:
154 		/* Start on the command line. */
155 		if (argv[0][0] == '-')
156 			errx(1, "negative numbers aren't permitted.");
157 
158 		errno = 0;
159 		start = strtoumax(argv[0], &p, 0);
160 		if (errno)
161 			err(1, "%s", argv[0]);
162 		if (*p != '\0')
163 			errx(1, "%s: illegal numeric format.", argv[0]);
164 		break;
165 	case 0:
166 		start = read_num_buf();
167 		break;
168 	default:
169 		usage();
170 	}
171 
172 	if (start > stop)
173 		errx(1, "start value must be less than stop value.");
174 	primes(start, stop);
175 	return (0);
176 }
177 
178 /*
179  * read_num_buf --
180  *	This routine returns a number n, where 0 <= n && n <= BIG.
181  */
182 static ubig
183 read_num_buf(void)
184 {
185 	ubig val;
186 	char *p, buf[LINE_MAX];		/* > max number of digits. */
187 
188 	for (;;) {
189 		if (fgets(buf, sizeof(buf), stdin) == NULL) {
190 			if (ferror(stdin))
191 				err(1, "stdin");
192 			exit(0);
193 		}
194 		for (p = buf; isblank(*p); ++p);
195 		if (*p == '\n' || *p == '\0')
196 			continue;
197 		if (*p == '-')
198 			errx(1, "negative numbers aren't permitted.");
199 		errno = 0;
200 		val = strtoumax(buf, &p, 0);
201 		if (errno)
202 			err(1, "%s", buf);
203 		if (*p != '\n')
204 			errx(1, "%s: illegal numeric format.", buf);
205 		return (val);
206 	}
207 }
208 
209 /*
210  * primes - sieve and print primes from start up to and but not including stop
211  */
212 static void
213 primes(ubig start, ubig stop)
214 {
215 	char *q;		/* sieve spot */
216 	ubig factor;		/* index and factor */
217 	char *tab_lim;		/* the limit to sieve on the table */
218 	const ubig *p;		/* prime table pointer */
219 	ubig fact_lim;		/* highest prime for current block */
220 	ubig mod;		/* temp storage for mod */
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 BIG.
226 	 */
227 	if (start < 3) {
228 		start = (ubig)2;
229 	}
230 	if (stop < 3) {
231 		stop = (ubig)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 "\n" : "%" PRIu64 "\n", factor);
256 			}
257 		}
258 		/* return early if we are done */
259 		if (p <= pr_limit) {
260 			return;
261 		}
262 		start = *pr_limit+2;
263 	}
264 
265 	/*
266 	 * we shall sieve a bytemap window, note primes and move the window
267 	 * upward until we pass the stop point
268 	 */
269 	while (start < stop) {
270 		/*
271 		 * factor out 3, 5, 7, 11 and 13
272 		 */
273 		/* initial pattern copy */
274 		factor = (start%(2*3*5*7*11*13))/2; /* starting copy spot */
275 		memcpy(table, &pattern[factor], pattern_size-factor);
276 		/* main block pattern copies */
277 		for (fact_lim=pattern_size-factor;
278 		    fact_lim+pattern_size<=TABSIZE; fact_lim+=pattern_size) {
279 			memcpy(&table[fact_lim], pattern, pattern_size);
280 		}
281 		/* final block pattern copy */
282 		memcpy(&table[fact_lim], pattern, TABSIZE-fact_lim);
283 
284 		/*
285 		 * sieve for primes 17 and higher
286 		 */
287 		/* note highest useful factor and sieve spot */
288 		if (stop-start > TABSIZE+TABSIZE) {
289 			tab_lim = &table[TABSIZE]; /* sieve it all */
290 			fact_lim = sqrt(start+1.0+TABSIZE+TABSIZE);
291 		} else {
292 			tab_lim = &table[(stop-start)/2]; /* partial sieve */
293 			fact_lim = sqrt(stop+1.0);
294 		}
295 		/* sieve for factors >= 17 */
296 		factor = 17;	/* 17 is first prime to use */
297 		p = &prime[7];	/* 19 is next prime, pi(19)=7 */
298 		do {
299 			/* determine the factor's initial sieve point */
300 			mod = start%factor;
301 			if (mod & 0x1) {
302 				q = &table[(factor-mod)/2];
303 			} else {
304 				q = &table[mod ? factor-(mod/2) : 0];
305 			}
306 			/* sive for our current factor */
307 			for ( ; q < tab_lim; q += factor) {
308 				*q = '\0'; /* sieve out a spot */
309 			}
310 			factor = *p++;
311 		} while (factor <= fact_lim);
312 
313 		/*
314 		 * print generated primes
315 		 */
316 		for (q = table; q < tab_lim; ++q, start+=2) {
317 			if (*q) {
318 				if (start > SIEVEMAX) {
319 					if (!isprime(start))
320 						continue;
321 				}
322 				printf(hflag ? "%" PRIx64 "\n" : "%" PRIu64 "\n", start);
323 			}
324 		}
325 	}
326 }
327 
328 static void
329 usage(void)
330 {
331 	fprintf(stderr, "usage: primes [-h] [start [stop]]\n");
332 	exit(1);
333 }
334