/* Prime number generator. Copyright 1991-1999, R.Harmsen Command line interface, for MSDOS or UNIX. Input: A starting point, "lower bound", and a range. Example: prm 300 2000 generates primes between 300 and 2300. The two parameters may be specified as command line arguments, as in the example above, or if run without arguments, the program prompts for them. Works for number up to 9 digits. Known bug: Entering non-numeric data to the prompts may cause the program to hang. */ #include #include #include #include #define COLUMNS 7 #define LINES 64 #define PLINES (LINES - 3) static char *outfilename = "prm.lst"; void show (unsigned long x, int flsh); int main (int argc, char **argv) { register unsigned long x, t, d, m; register int p; remove(outfilename); if (argc == 3) { x = atol(argv[1]); t = atol(argv[2]); } else { unsigned long tempx, tempt; fprintf (stderr, "lower bound? "); scanf ("%ld", &tempx); fprintf (stderr, "\nrange? "); scanf ("%ld", &tempt); t = tempt; x = tempx; } t += x; x += 6; x -= x % 6; x--; if (x < 23) { show (2, 0); show (3, 0); show (5, 0); show (7, 0); show (11, 0); show (13, 0); show (17, 0); show (19, 0); x = 23; } for (; x < t; x += 4) { m = (unsigned long) sqrt (x) + 2; d = 5; p = 1; for (; p && d < m; d += 6) if (x % d == 0 || x % (d + 2) == 0) p = 0; if (p) show (x, 0); x += 2; d = 5; p = 1; for (; p && d < m; d += 6) if (x % d == 0 || x % (d + 2) == 0) p = 0; if (p) show (x, 0); } show (0, 1); return 0; } void show (unsigned long x, int flsh) { static unsigned long b[COLUMNS * PLINES]; static unsigned long *p = b; if (!flsh) *p++ = x; if (p >= (b + COLUMNS * PLINES) || flsh) { register unsigned long *m; register int l; FILE *fp; if ((fp = fopen(outfilename, "a")) == NULL) { fprintf(stderr, "Can't open %s,\nerrno %d = %s\n", outfilename, errno, strerror(errno)); exit(1); } for (l = 0; l < PLINES; l++) { for (m = b + l; m < p; m += PLINES) { fprintf (fp, "%11ld", *m); fprintf (stdout, "%11ld", *m); } fprintf (fp, "\n"); fprintf (stdout, "\n"); } for (l = 0; l < LINES - PLINES; l++) { fprintf (fp, "\n"); fprintf (stdout, "\n"); } p = b; fclose(fp); } }