Home | History | Annotate | Line # | Download | only in primes
primes.c revision 1.5
      1  1.5  cgd /*	$NetBSD: primes.c,v 1.5 1995/04/24 12:24:47 cgd Exp $	*/
      2  1.4  cgd 
      3  1.1  cgd /*
      4  1.4  cgd  * Copyright (c) 1989, 1993
      5  1.4  cgd  *	The Regents of the University of California.  All rights reserved.
      6  1.1  cgd  *
      7  1.1  cgd  * This code is derived from software contributed to Berkeley by
      8  1.1  cgd  * Landon Curt Noll.
      9  1.1  cgd  *
     10  1.1  cgd  * Redistribution and use in source and binary forms, with or without
     11  1.1  cgd  * modification, are permitted provided that the following conditions
     12  1.1  cgd  * are met:
     13  1.1  cgd  * 1. Redistributions of source code must retain the above copyright
     14  1.1  cgd  *    notice, this list of conditions and the following disclaimer.
     15  1.1  cgd  * 2. Redistributions in binary form must reproduce the above copyright
     16  1.1  cgd  *    notice, this list of conditions and the following disclaimer in the
     17  1.1  cgd  *    documentation and/or other materials provided with the distribution.
     18  1.1  cgd  * 3. All advertising materials mentioning features or use of this software
     19  1.1  cgd  *    must display the following acknowledgement:
     20  1.1  cgd  *	This product includes software developed by the University of
     21  1.1  cgd  *	California, Berkeley and its contributors.
     22  1.1  cgd  * 4. Neither the name of the University nor the names of its contributors
     23  1.1  cgd  *    may be used to endorse or promote products derived from this software
     24  1.1  cgd  *    without specific prior written permission.
     25  1.1  cgd  *
     26  1.1  cgd  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  1.1  cgd  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  1.1  cgd  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  1.1  cgd  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  1.1  cgd  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  1.1  cgd  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  1.1  cgd  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  1.1  cgd  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  1.1  cgd  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  1.1  cgd  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  1.1  cgd  * SUCH DAMAGE.
     37  1.1  cgd  */
     38  1.1  cgd 
     39  1.1  cgd #ifndef lint
     40  1.4  cgd static char copyright[] =
     41  1.4  cgd "@(#) Copyright (c) 1989, 1993\n\
     42  1.4  cgd 	The Regents of the University of California.  All rights reserved.\n";
     43  1.1  cgd #endif /* not lint */
     44  1.1  cgd 
     45  1.1  cgd #ifndef lint
     46  1.4  cgd #if 0
     47  1.4  cgd static char sccsid[] = "@(#)primes.c	8.4 (Berkeley) 3/21/94";
     48  1.4  cgd #else
     49  1.5  cgd static char rcsid[] = "$NetBSD: primes.c,v 1.5 1995/04/24 12:24:47 cgd Exp $";
     50  1.4  cgd #endif
     51  1.1  cgd #endif /* not lint */
     52  1.1  cgd 
     53  1.1  cgd /*
     54  1.1  cgd  * primes - generate a table of primes between two values
     55  1.1  cgd  *
     56  1.4  cgd  * By: Landon Curt Noll chongo (at) toad.com, ...!{sun,tolsoft}!hoptoad!chongo
     57  1.1  cgd  *
     58  1.4  cgd  * chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
     59  1.1  cgd  *
     60  1.1  cgd  * usage:
     61  1.1  cgd  *	primes [start [stop]]
     62  1.1  cgd  *
     63  1.1  cgd  *	Print primes >= start and < stop.  If stop is omitted,
     64  1.1  cgd  *	the value 4294967295 (2^32-1) is assumed.  If start is
     65  1.1  cgd  *	omitted, start is read from standard input.
     66  1.1  cgd  *
     67  1.1  cgd  * validation check: there are 664579 primes between 0 and 10^7
     68  1.1  cgd  */
     69  1.1  cgd 
     70  1.4  cgd #include <ctype.h>
     71  1.4  cgd #include <err.h>
     72  1.4  cgd #include <errno.h>
     73  1.4  cgd #include <limits.h>
     74  1.1  cgd #include <math.h>
     75  1.1  cgd #include <memory.h>
     76  1.4  cgd #include <stdio.h>
     77  1.4  cgd #include <stdlib.h>
     78  1.4  cgd 
     79  1.1  cgd #include "primes.h"
     80  1.1  cgd 
     81  1.1  cgd /*
     82  1.1  cgd  * Eratosthenes sieve table
     83  1.1  cgd  *
     84  1.1  cgd  * We only sieve the odd numbers.  The base of our sieve windows are always
     85  1.1  cgd  * odd.  If the base of table is 1, table[i] represents 2*i-1.  After the
     86  1.1  cgd  * sieve, table[i] == 1 if and only iff 2*i-1 is prime.
     87  1.1  cgd  *
     88  1.1  cgd  * We make TABSIZE large to reduce the overhead of inner loop setup.
     89  1.1  cgd  */
     90  1.1  cgd char table[TABSIZE];	 /* Eratosthenes sieve of odd numbers */
     91  1.1  cgd 
     92  1.1  cgd /*
     93  1.1  cgd  * prime[i] is the (i-1)th prime.
     94  1.1  cgd  *
     95  1.1  cgd  * We are able to sieve 2^32-1 because this byte table yields all primes
     96  1.1  cgd  * up to 65537 and 65537^2 > 2^32-1.
     97  1.1  cgd  */
     98  1.1  cgd extern ubig prime[];
     99  1.1  cgd extern ubig *pr_limit;		/* largest prime in the prime array */
    100  1.1  cgd 
    101  1.1  cgd /*
    102  1.1  cgd  * To avoid excessive sieves for small factors, we use the table below to
    103  1.1  cgd  * setup our sieve blocks.  Each element represents a odd number starting
    104  1.1  cgd  * with 1.  All non-zero elements are factors of 3, 5, 7, 11 and 13.
    105  1.1  cgd  */
    106  1.1  cgd extern char pattern[];
    107  1.1  cgd extern int pattern_size;	/* length of pattern array */
    108  1.1  cgd 
    109  1.4  cgd void	primes __P((ubig, ubig));
    110  1.4  cgd ubig	read_num_buf __P((void));
    111  1.4  cgd void	usage __P((void));
    112  1.1  cgd 
    113  1.4  cgd int
    114  1.1  cgd main(argc, argv)
    115  1.4  cgd 	int argc;
    116  1.4  cgd 	char *argv[];
    117  1.1  cgd {
    118  1.4  cgd 	ubig start;		/* where to start generating */
    119  1.4  cgd 	ubig stop;		/* don't generate at or above this value */
    120  1.4  cgd 	int ch;
    121  1.4  cgd 	char *p;
    122  1.4  cgd 
    123  1.4  cgd 	while ((ch = getopt(argc, argv, "")) != EOF)
    124  1.4  cgd 		switch (ch) {
    125  1.4  cgd 		case '?':
    126  1.4  cgd 		default:
    127  1.4  cgd 			usage();
    128  1.4  cgd 		}
    129  1.4  cgd 	argc -= optind;
    130  1.4  cgd 	argv += optind;
    131  1.1  cgd 
    132  1.1  cgd 	start = 0;
    133  1.1  cgd 	stop = BIG;
    134  1.1  cgd 
    135  1.4  cgd 	/*
    136  1.4  cgd 	 * Convert low and high args.  Strtoul(3) sets errno to
    137  1.4  cgd 	 * ERANGE if the number is too large, but, if there's
    138  1.4  cgd 	 * a leading minus sign it returns the negation of the
    139  1.4  cgd 	 * result of the conversion, which we'd rather disallow.
    140  1.4  cgd 	 */
    141  1.4  cgd 	switch (argc) {
    142  1.4  cgd 	case 2:
    143  1.4  cgd 		/* Start and stop supplied on the command line. */
    144  1.4  cgd 		if (argv[0][0] == '-' || argv[1][0] == '-')
    145  1.4  cgd 			errx(1, "negative numbers aren't permitted.");
    146  1.4  cgd 
    147  1.4  cgd 		errno = 0;
    148  1.4  cgd 		start = strtoul(argv[0], &p, 10);
    149  1.4  cgd 		if (errno)
    150  1.4  cgd 			err(1, "%s", argv[0]);
    151  1.4  cgd 		if (*p != '\0')
    152  1.4  cgd 			errx(1, "%s: illegal numeric format.", argv[0]);
    153  1.4  cgd 
    154  1.4  cgd 		errno = 0;
    155  1.4  cgd 		stop = strtoul(argv[1], &p, 10);
    156  1.4  cgd 		if (errno)
    157  1.4  cgd 			err(1, "%s", argv[1]);
    158  1.4  cgd 		if (*p != '\0')
    159  1.4  cgd 			errx(1, "%s: illegal numeric format.", argv[1]);
    160  1.4  cgd 		break;
    161  1.4  cgd 	case 1:
    162  1.4  cgd 		/* Start on the command line. */
    163  1.4  cgd 		if (argv[0][0] == '-')
    164  1.4  cgd 			errx(1, "negative numbers aren't permitted.");
    165  1.4  cgd 
    166  1.4  cgd 		errno = 0;
    167  1.4  cgd 		start = strtoul(argv[0], &p, 10);
    168  1.4  cgd 		if (errno)
    169  1.4  cgd 			err(1, "%s", argv[0]);
    170  1.4  cgd 		if (*p != '\0')
    171  1.4  cgd 			errx(1, "%s: illegal numeric format.", argv[0]);
    172  1.4  cgd 		break;
    173  1.4  cgd 	case 0:
    174  1.4  cgd 		start = read_num_buf();
    175  1.4  cgd 		break;
    176  1.4  cgd 	default:
    177  1.4  cgd 		usage();
    178  1.4  cgd 	}
    179  1.1  cgd 
    180  1.4  cgd 	if (start > stop)
    181  1.4  cgd 		errx(1, "start value must be less than stop value.");
    182  1.1  cgd 	primes(start, stop);
    183  1.1  cgd 	exit(0);
    184  1.1  cgd }
    185  1.1  cgd 
    186  1.1  cgd /*
    187  1.4  cgd  * read_num_buf --
    188  1.4  cgd  *	This routine returns a number n, where 0 <= n && n <= BIG.
    189  1.1  cgd  */
    190  1.4  cgd ubig
    191  1.4  cgd read_num_buf()
    192  1.1  cgd {
    193  1.4  cgd 	ubig val;
    194  1.4  cgd 	char *p, buf[100];		/* > max number of digits. */
    195  1.1  cgd 
    196  1.4  cgd 	for (;;) {
    197  1.4  cgd 		if (fgets(buf, sizeof(buf), stdin) == NULL) {
    198  1.4  cgd 			if (ferror(stdin))
    199  1.4  cgd 				err(1, "stdin");
    200  1.4  cgd 			exit(0);
    201  1.1  cgd 		}
    202  1.4  cgd 		for (p = buf; isblank(*p); ++p);
    203  1.4  cgd 		if (*p == '\n' || *p == '\0')
    204  1.1  cgd 			continue;
    205  1.4  cgd 		if (*p == '-')
    206  1.4  cgd 			errx(1, "negative numbers aren't permitted.");
    207  1.4  cgd 		errno = 0;
    208  1.4  cgd 		val = strtoul(buf, &p, 10);
    209  1.4  cgd 		if (errno)
    210  1.4  cgd 			err(1, "%s", buf);
    211  1.4  cgd 		if (*p != '\n')
    212  1.4  cgd 			errx(1, "%s: illegal numeric format.", buf);
    213  1.4  cgd 		return (val);
    214  1.4  cgd 	}
    215  1.1  cgd }
    216  1.1  cgd 
    217  1.1  cgd /*
    218  1.1  cgd  * primes - sieve and print primes from start up to and but not including stop
    219  1.1  cgd  */
    220  1.1  cgd void
    221  1.1  cgd primes(start, stop)
    222  1.1  cgd 	ubig start;	/* where to start generating */
    223  1.1  cgd 	ubig stop;	/* don't generate at or above this value */
    224  1.1  cgd {
    225  1.1  cgd 	register char *q;		/* sieve spot */
    226  1.1  cgd 	register ubig factor;		/* index and factor */
    227  1.1  cgd 	register char *tab_lim;		/* the limit to sieve on the table */
    228  1.1  cgd 	register ubig *p;		/* prime table pointer */
    229  1.1  cgd 	register ubig fact_lim;		/* highest prime for current block */
    230  1.1  cgd 
    231  1.1  cgd 	/*
    232  1.4  cgd 	 * A number of systems can not convert double values into unsigned
    233  1.4  cgd 	 * longs when the values are larger than the largest signed value.
    234  1.4  cgd 	 * We don't have this problem, so we can go all the way to BIG.
    235  1.1  cgd 	 */
    236  1.1  cgd 	if (start < 3) {
    237  1.1  cgd 		start = (ubig)2;
    238  1.1  cgd 	}
    239  1.1  cgd 	if (stop < 3) {
    240  1.1  cgd 		stop = (ubig)2;
    241  1.1  cgd 	}
    242  1.1  cgd 	if (stop <= start) {
    243  1.1  cgd 		return;
    244  1.1  cgd 	}
    245  1.1  cgd 
    246  1.1  cgd 	/*
    247  1.1  cgd 	 * be sure that the values are odd, or 2
    248  1.1  cgd 	 */
    249  1.1  cgd 	if (start != 2 && (start&0x1) == 0) {
    250  1.1  cgd 		++start;
    251  1.1  cgd 	}
    252  1.1  cgd 	if (stop != 2 && (stop&0x1) == 0) {
    253  1.1  cgd 		++stop;
    254  1.1  cgd 	}
    255  1.1  cgd 
    256  1.1  cgd 	/*
    257  1.1  cgd 	 * quick list of primes <= pr_limit
    258  1.1  cgd 	 */
    259  1.1  cgd 	if (start <= *pr_limit) {
    260  1.1  cgd 		/* skip primes up to the start value */
    261  1.1  cgd 		for (p = &prime[0], factor = prime[0];
    262  1.4  cgd 		    factor < stop && p <= pr_limit; factor = *(++p)) {
    263  1.1  cgd 			if (factor >= start) {
    264  1.1  cgd 				printf("%u\n", factor);
    265  1.1  cgd 			}
    266  1.1  cgd 		}
    267  1.1  cgd 		/* return early if we are done */
    268  1.1  cgd 		if (p <= pr_limit) {
    269  1.1  cgd 			return;
    270  1.1  cgd 		}
    271  1.1  cgd 		start = *pr_limit+2;
    272  1.1  cgd 	}
    273  1.1  cgd 
    274  1.1  cgd 	/*
    275  1.1  cgd 	 * we shall sieve a bytemap window, note primes and move the window
    276  1.1  cgd 	 * upward until we pass the stop point
    277  1.1  cgd 	 */
    278  1.1  cgd 	while (start < stop) {
    279  1.1  cgd 		/*
    280  1.1  cgd 		 * factor out 3, 5, 7, 11 and 13
    281  1.1  cgd 		 */
    282  1.1  cgd 		/* initial pattern copy */
    283  1.1  cgd 		factor = (start%(2*3*5*7*11*13))/2; /* starting copy spot */
    284  1.1  cgd 		memcpy(table, &pattern[factor], pattern_size-factor);
    285  1.1  cgd 		/* main block pattern copies */
    286  1.1  cgd 		for (fact_lim=pattern_size-factor;
    287  1.4  cgd 		    fact_lim+pattern_size<=TABSIZE; fact_lim+=pattern_size) {
    288  1.1  cgd 			memcpy(&table[fact_lim], pattern, pattern_size);
    289  1.1  cgd 		}
    290  1.1  cgd 		/* final block pattern copy */
    291  1.1  cgd 		memcpy(&table[fact_lim], pattern, TABSIZE-fact_lim);
    292  1.1  cgd 
    293  1.1  cgd 		/*
    294  1.1  cgd 		 * sieve for primes 17 and higher
    295  1.1  cgd 		 */
    296  1.1  cgd 		/* note highest useful factor and sieve spot */
    297  1.1  cgd 		if (stop-start > TABSIZE+TABSIZE) {
    298  1.1  cgd 			tab_lim = &table[TABSIZE]; /* sieve it all */
    299  1.1  cgd 			fact_lim = (int)sqrt(
    300  1.1  cgd 					(double)(start)+TABSIZE+TABSIZE+1.0);
    301  1.1  cgd 		} else {
    302  1.1  cgd 			tab_lim = &table[(stop-start)/2]; /* partial sieve */
    303  1.1  cgd 			fact_lim = (int)sqrt((double)(stop)+1.0);
    304  1.1  cgd 		}
    305  1.1  cgd 		/* sieve for factors >= 17 */
    306  1.1  cgd 		factor = 17;	/* 17 is first prime to use */
    307  1.1  cgd 		p = &prime[7];	/* 19 is next prime, pi(19)=7 */
    308  1.1  cgd 		do {
    309  1.1  cgd 			/* determine the factor's initial sieve point */
    310  1.1  cgd 			q = (char *)(start%factor); /* temp storage for mod */
    311  1.5  cgd 			if ((long)q & 0x1) {
    312  1.5  cgd 				q = &table[(factor-(long)q)/2];
    313  1.1  cgd 			} else {
    314  1.5  cgd 				q = &table[q ? factor-((long)q/2) : 0];
    315  1.1  cgd 			}
    316  1.1  cgd 			/* sive for our current factor */
    317  1.1  cgd 			for ( ; q < tab_lim; q += factor) {
    318  1.1  cgd 				*q = '\0'; /* sieve out a spot */
    319  1.1  cgd 			}
    320  1.1  cgd 		} while ((factor=(ubig)(*(p++))) <= fact_lim);
    321  1.1  cgd 
    322  1.1  cgd 		/*
    323  1.1  cgd 		 * print generated primes
    324  1.1  cgd 		 */
    325  1.1  cgd 		for (q = table; q < tab_lim; ++q, start+=2) {
    326  1.1  cgd 			if (*q) {
    327  1.1  cgd 				printf("%u\n", start);
    328  1.1  cgd 			}
    329  1.1  cgd 		}
    330  1.1  cgd 	}
    331  1.4  cgd }
    332  1.4  cgd 
    333  1.4  cgd void
    334  1.4  cgd usage()
    335  1.4  cgd {
    336  1.4  cgd 	(void)fprintf(stderr, "usage: primes [start [stop]]\n");
    337  1.4  cgd 	exit(1);
    338  1.1  cgd }
    339