Home | History | Annotate | Line # | Download | only in primes
primes.c revision 1.2
      1 /*
      2  * Copyright (c) 1989 The Regents of the University of California.
      3  * 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 char copyright[] =
     39 "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
     40  All rights reserved.\n";
     41 #endif /* not lint */
     42 
     43 #ifndef lint
     44 /*static char sccsid[] = "from: @(#)primes.c	5.4 (Berkeley) 6/1/90";*/
     45 static char rcsid[] = "$Id: primes.c,v 1.2 1993/08/01 18:53:04 mycroft Exp $";
     46 #endif /* not lint */
     47 
     48 /*
     49  * primes - generate a table of primes between two values
     50  *
     51  * By: Landon Curt Noll   chongo (at) toad.com,   ...!{sun,tolsoft}!hoptoad!chongo
     52  *
     53  *   chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
     54  *
     55  * usage:
     56  *	primes [start [stop]]
     57  *
     58  *	Print primes >= start and < stop.  If stop is omitted,
     59  *	the value 4294967295 (2^32-1) is assumed.  If start is
     60  *	omitted, start is read from standard input.
     61  *
     62  *	Prints "ouch" if start or stop is bogus.
     63  *
     64  * validation check: there are 664579 primes between 0 and 10^7
     65  */
     66 
     67 #include <stdio.h>
     68 #include <math.h>
     69 #include <memory.h>
     70 #include <ctype.h>
     71 #include "primes.h"
     72 
     73 /*
     74  * Eratosthenes sieve table
     75  *
     76  * We only sieve the odd numbers.  The base of our sieve windows are always
     77  * odd.  If the base of table is 1, table[i] represents 2*i-1.  After the
     78  * sieve, table[i] == 1 if and only iff 2*i-1 is prime.
     79  *
     80  * We make TABSIZE large to reduce the overhead of inner loop setup.
     81  */
     82 char table[TABSIZE];	 /* Eratosthenes sieve of odd numbers */
     83 
     84 /*
     85  * prime[i] is the (i-1)th prime.
     86  *
     87  * We are able to sieve 2^32-1 because this byte table yields all primes
     88  * up to 65537 and 65537^2 > 2^32-1.
     89  */
     90 extern ubig prime[];
     91 extern ubig *pr_limit;		/* largest prime in the prime array */
     92 
     93 /*
     94  * To avoid excessive sieves for small factors, we use the table below to
     95  * setup our sieve blocks.  Each element represents a odd number starting
     96  * with 1.  All non-zero elements are factors of 3, 5, 7, 11 and 13.
     97  */
     98 extern char pattern[];
     99 extern int pattern_size;	/* length of pattern array */
    100 
    101 #define MAX_LINE 255    /* max line allowed on stdin */
    102 
    103 char *read_num_buf();	 /* read a number buffer */
    104 void primes();		 /* print the primes in range */
    105 char *program;		 /* our name */
    106 
    107 main(argc, argv)
    108 	int argc;	/* arg count */
    109 	char *argv[];	/* args */
    110 {
    111 	char buf[MAX_LINE+1];   /* input buffer */
    112 	char *ret;	/* return result */
    113 	ubig start;	/* where to start generating */
    114 	ubig stop;	/* don't generate at or above this value */
    115 
    116 	/*
    117 	 * parse args
    118 	 */
    119 	program = argv[0];
    120 	start = 0;
    121 	stop = BIG;
    122 	if (argc == 3) {
    123 		/* convert low and high args */
    124 		if (read_num_buf(NULL, argv[1]) == NULL) {
    125 			fprintf(stderr, "%s: ouch\n", program);
    126 			exit(1);
    127 		}
    128 		if (read_num_buf(NULL, argv[2]) == NULL) {
    129 			fprintf(stderr, "%s: ouch\n", program);
    130 			exit(1);
    131 		}
    132 		if (sscanf(argv[1], "%ld", &start) != 1) {
    133 			fprintf(stderr, "%s: ouch\n", program);
    134 			exit(1);
    135 		}
    136 		if (sscanf(argv[2], "%ld", &stop) != 1) {
    137 			fprintf(stderr, "%s: ouch\n", program);
    138 			exit(1);
    139 		}
    140 
    141 	} else if (argc == 2) {
    142 		/* convert low arg */
    143 		if (read_num_buf(NULL, argv[1]) == NULL) {
    144 			fprintf(stderr, "%s: ouch\n", program);
    145 			exit(1);
    146 		}
    147 		if (sscanf(argv[1], "%ld", &start) != 1) {
    148 			fprintf(stderr, "%s: ouch\n", program);
    149 			exit(1);
    150 		}
    151 
    152 	} else {
    153 		/* read input until we get a good line */
    154 		if (read_num_buf(stdin, buf) != NULL) {
    155 
    156 			/* convert the buffer */
    157 			if (sscanf(buf, "%ld", &start) != 1) {
    158 				fprintf(stderr, "%s: ouch\n", program);
    159 				exit(1);
    160 			}
    161 		} else {
    162 			exit(0);
    163 		}
    164 	}
    165 	if (start > stop) {
    166 		fprintf(stderr, "%s: ouch\n", program);
    167 		exit(1);
    168 	}
    169 	primes(start, stop);
    170 	exit(0);
    171 }
    172 
    173 /*
    174  * read_num_buf - read a number buffer from a stream
    175  *
    176  * Read a number on a line of the form:
    177  *
    178  *	^[ \t]*\(+?[0-9][0-9]\)*.*$
    179  *
    180  * where ? is a 1-or-0 operator and the number is within \( \).
    181  *
    182  * If does not match the above pattern, it is ignored and a new
    183  * line is read.  If the number is too large or small, we will
    184  * print ouch and read a new line.
    185  *
    186  * We have to be very careful on how we check the magnitude of the
    187  * input.  We can not use numeric checks because of the need to
    188  * check values against maximum numeric values.
    189  *
    190  * This routine will return a line containing a ascii number between
    191  * 0 and BIG, or it will return NULL.
    192  *
    193  * If the stream is NULL then buf will be processed as if were
    194  * a single line stream.
    195  *
    196  * returns:
    197  *	char *	pointer to leading digit or +
    198  *	NULL	EOF or error
    199  */
    200 char *
    201 read_num_buf(input, buf)
    202 	FILE *input;		/* input stream or NULL */
    203 	char *buf;		/* input buffer */
    204 {
    205 	static char limit[MAX_LINE+1];	/* ascii value of BIG */
    206 	static int limit_len;		/* digit count of limit */
    207 	int len;			/* digits in input (excluding +/-) */
    208 	char *s;	/* line start marker */
    209 	char *d;	/* first digit, skip +/- */
    210 	char *p;	/* scan pointer */
    211 	char *z;	/* zero scan pointer */
    212 
    213 	/* form the ascii value of SEMIBIG if needed */
    214 	if (!isascii(limit[0]) || !isdigit(limit[0])) {
    215 		sprintf(limit, "%ld", SEMIBIG);
    216 		limit_len = strlen(limit);
    217 	}
    218 
    219 	/*
    220 	 * the search for a good line
    221 	 */
    222 	if (input != NULL && fgets(buf, MAX_LINE, input) == NULL) {
    223 		/* error or EOF */
    224 		return NULL;
    225 	}
    226 	do {
    227 
    228 		/* ignore leading whitespace */
    229 		for (s=buf; *s && s < buf+MAX_LINE; ++s) {
    230 			if (!isascii(*s) || !isspace(*s)) {
    231 				break;
    232 			}
    233 		}
    234 
    235 		/* object if - */
    236 		if (*s == '-') {
    237 			fprintf(stderr, "%s: ouch\n", program);
    238 			continue;
    239 		}
    240 
    241 		/* skip over any leading + */
    242 		if (*s == '+') {
    243 			d = s+1;
    244 		} else {
    245 			d = s;
    246 		}
    247 
    248 		/* note leading zeros */
    249 		for (z=d; *z && z < buf+MAX_LINE; ++z) {
    250 			if (*z != '0') {
    251 				break;
    252 			}
    253 		}
    254 
    255 		/* scan for the first non-digit/non-plus/non-minus */
    256 		for (p=d; *p && p < buf+MAX_LINE; ++p) {
    257 			if (!isascii(*p) || !isdigit(*p)) {
    258 				break;
    259 			}
    260 		}
    261 
    262 		/* ignore empty lines */
    263 		if (p == d) {
    264 			continue;
    265 		}
    266 		*p = '\0';
    267 
    268 		/* object if too many digits */
    269 		len = strlen(z);
    270 		len = (len<=0) ? 1 : len;
    271 		/* accept if digit count is below limit */
    272 		if (len < limit_len) {
    273 			/* we have good input */
    274 			return s;
    275 
    276 		/* reject very large numbers */
    277 		} else if (len > limit_len) {
    278 			fprintf(stderr, "%s: ouch\n", program);
    279 			continue;
    280 
    281 		/* carefully check against near limit numbers */
    282 		} else if (strcmp(z, limit) > 0) {
    283 			fprintf(stderr, "%s: ouch\n", program);
    284 			continue;
    285 		}
    286 		/* number is near limit, but is under it */
    287 		return s;
    288 	} while (input != NULL && fgets(buf, MAX_LINE, input) != NULL);
    289 
    290 	/* error or EOF */
    291 	return NULL;
    292 }
    293 
    294 /*
    295  * primes - sieve and print primes from start up to and but not including stop
    296  */
    297 void
    298 primes(start, stop)
    299 	ubig start;	/* where to start generating */
    300 	ubig stop;	/* don't generate at or above this value */
    301 {
    302 	register char *q;		/* sieve spot */
    303 	register ubig factor;		/* index and factor */
    304 	register char *tab_lim;		/* the limit to sieve on the table */
    305 	register ubig *p;		/* prime table pointer */
    306 	register ubig fact_lim;		/* highest prime for current block */
    307 
    308 	/*
    309 	 * A number of systems can not convert double values
    310 	 * into unsigned longs when the values are larger than
    311 	 * the largest signed value.  Thus we take case when
    312 	 * the double is larger than the value SEMIBIG. *sigh*
    313 	 */
    314 	if (start < 3) {
    315 		start = (ubig)2;
    316 	}
    317 	if (stop < 3) {
    318 		stop = (ubig)2;
    319 	}
    320 	if (stop <= start) {
    321 		return;
    322 	}
    323 
    324 	/*
    325 	 * be sure that the values are odd, or 2
    326 	 */
    327 	if (start != 2 && (start&0x1) == 0) {
    328 		++start;
    329 	}
    330 	if (stop != 2 && (stop&0x1) == 0) {
    331 		++stop;
    332 	}
    333 
    334 	/*
    335 	 * quick list of primes <= pr_limit
    336 	 */
    337 	if (start <= *pr_limit) {
    338 		/* skip primes up to the start value */
    339 		for (p = &prime[0], factor = prime[0];
    340 		     factor < stop && p <= pr_limit;
    341 		     factor = *(++p)) {
    342 			if (factor >= start) {
    343 				printf("%u\n", factor);
    344 			}
    345 		}
    346 		/* return early if we are done */
    347 		if (p <= pr_limit) {
    348 			return;
    349 		}
    350 		start = *pr_limit+2;
    351 	}
    352 
    353 	/*
    354 	 * we shall sieve a bytemap window, note primes and move the window
    355 	 * upward until we pass the stop point
    356 	 */
    357 	while (start < stop) {
    358 		/*
    359 		 * factor out 3, 5, 7, 11 and 13
    360 		 */
    361 		/* initial pattern copy */
    362 		factor = (start%(2*3*5*7*11*13))/2; /* starting copy spot */
    363 		memcpy(table, &pattern[factor], pattern_size-factor);
    364 		/* main block pattern copies */
    365 		for (fact_lim=pattern_size-factor;
    366 		     fact_lim+pattern_size<=TABSIZE;
    367 		     fact_lim+=pattern_size) {
    368 			memcpy(&table[fact_lim], pattern, pattern_size);
    369 		}
    370 		/* final block pattern copy */
    371 		memcpy(&table[fact_lim], pattern, TABSIZE-fact_lim);
    372 
    373 		/*
    374 		 * sieve for primes 17 and higher
    375 		 */
    376 		/* note highest useful factor and sieve spot */
    377 		if (stop-start > TABSIZE+TABSIZE) {
    378 			tab_lim = &table[TABSIZE]; /* sieve it all */
    379 			fact_lim = (int)sqrt(
    380 					(double)(start)+TABSIZE+TABSIZE+1.0);
    381 		} else {
    382 			tab_lim = &table[(stop-start)/2]; /* partial sieve */
    383 			fact_lim = (int)sqrt((double)(stop)+1.0);
    384 		}
    385 		/* sieve for factors >= 17 */
    386 		factor = 17;	/* 17 is first prime to use */
    387 		p = &prime[7];	/* 19 is next prime, pi(19)=7 */
    388 		do {
    389 			/* determine the factor's initial sieve point */
    390 			q = (char *)(start%factor); /* temp storage for mod */
    391 			if ((int)q & 0x1) {
    392 				q = &table[(factor-(int)q)/2];
    393 			} else {
    394 				q = &table[q ? factor-((int)q/2) : 0];
    395 			}
    396 			/* sive for our current factor */
    397 			for ( ; q < tab_lim; q += factor) {
    398 				*q = '\0'; /* sieve out a spot */
    399 			}
    400 		} while ((factor=(ubig)(*(p++))) <= fact_lim);
    401 
    402 		/*
    403 		 * print generated primes
    404 		 */
    405 		for (q = table; q < tab_lim; ++q, start+=2) {
    406 			if (*q) {
    407 				printf("%u\n", start);
    408 			}
    409 		}
    410 	}
    411 }
    412