| 1 |
/* $Id: prime.c,v 1.8 2006/05/12 23:38:15 joko Exp $ */ |
| 2 |
|
| 3 |
#include <stdio.h> |
| 4 |
#include <stdlib.h> |
| 5 |
#include <limits.h> |
| 6 |
#include <errno.h> |
| 7 |
|
| 8 |
#define BOOL int |
| 9 |
#define TRUE 1 |
| 10 |
#define FALSE 0 |
| 11 |
|
| 12 |
#define PRINTPRIME(x) if (is_prime(x)) printf("%i\n", x) |
| 13 |
#define PRINTERROR(message) fprintf(stderr, "ERROR: %s\n", message) |
| 14 |
|
| 15 |
/* check for prime number */ |
| 16 |
BOOL is_prime(long int number) |
| 17 |
{ |
| 18 |
int i; |
| 19 |
|
| 20 |
/* negative values, 0 and 1 are never prime numbers */ |
| 21 |
if (number < 2) return FALSE; |
| 22 |
|
| 23 |
/* check all numbers 2..sqrt(number) for being a prime number */ |
| 24 |
for (i=2; i*i <= number; i++) { |
| 25 |
if ((number % i) == 0) |
| 26 |
return FALSE; |
| 27 |
} |
| 28 |
return TRUE; |
| 29 |
} |
| 30 |
|
| 31 |
/* convert from string to long int, with error checking */ |
| 32 |
long int convert_number(const char *nptr) { |
| 33 |
|
| 34 |
errno = 0; |
| 35 |
char * endptr; |
| 36 |
long int number = strtol(nptr, &endptr, 10); |
| 37 |
|
| 38 |
/* invalid characters? */ |
| 39 |
if (*endptr != '\0') { |
| 40 |
char message[254]; |
| 41 |
snprintf(message, 256, "Could not convert '%s' to a valid number.", nptr); |
| 42 |
PRINTERROR(message); |
| 43 |
exit(EXIT_FAILURE); |
| 44 |
} |
| 45 |
|
| 46 |
/* invalid range? */ |
| 47 |
/* if (number == LONG_MAX || number == LONG_MIN) { */ |
| 48 |
if (errno == ERANGE) { |
| 49 |
char message[254]; |
| 50 |
snprintf(message, 256, "Number is not in range of 'long int': %s", nptr); |
| 51 |
PRINTERROR(message); |
| 52 |
exit(EXIT_FAILURE); |
| 53 |
} |
| 54 |
|
| 55 |
return number; |
| 56 |
|
| 57 |
} |
| 58 |
|
| 59 |
int main(int argc, char * argv[]) |
| 60 |
{ |
| 61 |
|
| 62 |
if (argc == 1) { |
| 63 |
PRINTERROR("No arguments given."); |
| 64 |
exit(EXIT_FAILURE); |
| 65 |
} |
| 66 |
|
| 67 |
/* (3) range mode */ |
| 68 |
if (argc > 2) { |
| 69 |
long int i, j; |
| 70 |
i = convert_number(argv[1]); |
| 71 |
j = convert_number(argv[2]); |
| 72 |
for (i; i< j; i++) { |
| 73 |
PRINTPRIME(i); |
| 74 |
} |
| 75 |
|
| 76 |
/* other modes */ |
| 77 |
} else { |
| 78 |
|
| 79 |
/* try to open file for reading */ |
| 80 |
FILE * fp = fopen(argv[1], "r"); |
| 81 |
|
| 82 |
/* (1) test-single-number mode: first argument is not a filename */ |
| 83 |
if (fp == NULL) { |
| 84 |
long int number = convert_number(argv[1]); |
| 85 |
PRINTPRIME(number); |
| 86 |
|
| 87 |
/* (2) file mode: read numbers from file */ |
| 88 |
} else { |
| 89 |
char entry[11]; |
| 90 |
while (fgets(entry, 11, fp)) { |
| 91 |
long int number = convert_number(entry); |
| 92 |
PRINTPRIME(number); |
| 93 |
} |
| 94 |
fclose(fp); |
| 95 |
} |
| 96 |
} |
| 97 |
} |