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