--- joko/Uni/BSArch/01/prime.c 2006/05/12 20:38:15 1.5 +++ joko/Uni/BSArch/01/prime.c 2006/05/12 21:13:49 1.6 @@ -1,26 +1,40 @@ -/* $Id: prime.c,v 1.5 2006/05/12 20:38:15 joko Exp $ */ +/* $Id: prime.c,v 1.6 2006/05/12 21:13:49 joko Exp $ */ #include +#include +#include -#define PRINTPRIME(x) if(is_prime(x)) printf("%i\n", x) +#define BOOL int +#define TRUE 1 +#define FALSE 0 + +#define PRINTPRIME(x) if (is_prime(x)) printf("%i\n", x) #define PRINTERROR(message) fprintf(stderr, "ERROR: %s\n", message) /* check for prime number */ -int is_prime(int number) +BOOL is_prime(long int number) { int i; for (i=2; i*i <= number; i++) { if ((number % i) == 0) - return 0; + return FALSE; + } + return TRUE; +} + +/* convert from string to long, with error checking */ +long int convert_number(const char *nptr) { + long int number = strtol(nptr, (char **)NULL, 10); + if (number == LONG_MAX) { + PRINTERROR("Number '%s' is not in range of 'long int'."); } - return 1; } int main(int argc, char * argv[]) { if (argc == 1) { - PRINTERROR("No arguments given, will segfault under cygwin. :-)"); + PRINTERROR("No arguments given."); return -1; } @@ -40,7 +54,8 @@ /* (1) test-single-number mode: first argument is not a filename */ if (fp == NULL) { - PRINTPRIME(atoi(argv[1])); + /* PRINTPRIME(atoi(argv[1])); */ + PRINTPRIME(convert_number(argv[1])); /* (2) file mode: read numbers from file */ } else {