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