cc142f9bdf6465d6d2406429ad2a47cc838dba26
static char sccsid
[] = "@(#)primes.c 4.1 (Wollongong) %G%";
* Print all primes greater than argument (or number read from stdin).
* A free translation of 'primes.s'
#define TABSIZE 1000 /* size of sieve table */
#define BIG 4294967296. /* largest unsigned int */
char table
[TABSIZE
]; /* table for sieve of Eratosthenes */
int tabbits
= 8*TABSIZE
; /* number of bits in table */
unsigned start
; /* lowest number to test for prime */
char bittab
[] = { /* bit positions (to save shifting) */
01, 02, 04, 010, 020, 040, 0100, 0200
unsigned pt
[] = { /* primes < 100 */
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
unsigned factab
[] = { /* difference between succesive trial factors */
10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4,
2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4,
6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2
if (argc
>= 2) { /* get starting no. from arg */
if (sscanf(argv
[1], "%f", &fstart
) != 1
|| fstart
< 0.0 || fstart
>= BIG
) {
} else { /* get starting no. from stdin */
while ((i
= scanf("%f", &fstart
)) != 1
|| fstart
< 0.0 || fstart
>= BIG
) {
start
= (unsigned)fstart
;
* Quick list of primes < 100
for (fp
= pt
; *fp
< start
; fp
++)
while (++fp
< &pt
[sizeof(pt
) / sizeof(*pt
)]);
* Generate primes via sieve of Eratosthenes
for (p
= table
; p
< &table
[TABSIZE
]; p
++) /* clear sieve */
v
= (unsigned)sqrt((float)(start
+ tabbits
)); /* highest useful factor */
if (++fp
>= &factab
[sizeof(factab
) / sizeof(*factab
)])
for (i
= 0; i
< 8*TABSIZE
; i
+= 2) {
if ((table
[i
>>3] & bittab
[i
&07]) == 0)
* Insert all multiples of given factor into the sieve
off
= (quot
* factor
) - start
;
table
[i
>>3] |= bittab
[i
&07];
fprintf(stderr
, "Ouch.\n");