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