| 15 |
BOOL is_prime(long int number) |
BOOL is_prime(long int number) |
| 16 |
{ |
{ |
| 17 |
int i; |
int i; |
| 18 |
|
|
| 19 |
|
/* negative values are never prime numbers */ |
| 20 |
|
if (number < 2) return FALSE; |
| 21 |
|
|
| 22 |
|
/* check all numbers 2..sqrt(number) for being a prime number */ |
| 23 |
for (i=2; i*i <= number; i++) { |
for (i=2; i*i <= number; i++) { |
| 24 |
if ((number % i) == 0) |
if ((number % i) == 0) |
| 25 |
return FALSE; |
return FALSE; |
| 27 |
return TRUE; |
return TRUE; |
| 28 |
} |
} |
| 29 |
|
|
| 30 |
/* convert from string to long, with error checking */ |
/* convert from string to long int, with error checking */ |
| 31 |
long int convert_number(const char *nptr) { |
long int convert_number(const char *nptr) { |
| 32 |
long int number = strtol(nptr, (char **)NULL, 10); |
long int number = strtol(nptr, (char **)NULL, 10); |
| 33 |
if (number == LONG_MAX) { |
if (number == LONG_MAX || number == LONG_MIN) { |
| 34 |
PRINTERROR("Number '%s' is not in range of 'long int'."); |
char message[254]; |
| 35 |
|
snprintf(message, 256, "Number is not in range of 'long int': %s", nptr); |
| 36 |
|
PRINTERROR(message); |
| 37 |
|
exit(-1); |
| 38 |
} |
} |
| 39 |
} |
} |
| 40 |
|
|
| 43 |
|
|
| 44 |
if (argc == 1) { |
if (argc == 1) { |
| 45 |
PRINTERROR("No arguments given."); |
PRINTERROR("No arguments given."); |
| 46 |
return -1; |
exit(-1); |
| 47 |
} |
} |
| 48 |
|
|
| 49 |
/* (3) range mode */ |
/* (3) range mode */ |
| 50 |
if (argc > 2) { |
if (argc > 2) { |
| 51 |
int i, j; |
long int i, j; |
| 52 |
j = atoi(argv[2]); |
j = convert_number(argv[2]); |
| 53 |
for (i = atoi(argv[1]); i< j; i++) { |
for (i = convert_number(argv[1]); i< j; i++) { |
| 54 |
PRINTPRIME(i); |
PRINTPRIME(i); |
| 55 |
} |
} |
| 56 |
|
|
| 62 |
|
|
| 63 |
/* (1) test-single-number mode: first argument is not a filename */ |
/* (1) test-single-number mode: first argument is not a filename */ |
| 64 |
if (fp == NULL) { |
if (fp == NULL) { |
| 65 |
/* PRINTPRIME(atoi(argv[1])); */ |
long int number = convert_number(argv[1]); |
| 66 |
PRINTPRIME(convert_number(argv[1])); |
PRINTPRIME(number); |
| 67 |
|
|
| 68 |
/* (2) file mode: read numbers from file */ |
/* (2) file mode: read numbers from file */ |
| 69 |
} else { |
} else { |
| 70 |
char num[11]; |
char entry[11]; |
| 71 |
while (fgets(num, 11, fp)) { |
while (fgets(entry, 11, fp)) { |
| 72 |
printf("raw: %s\n", num); |
long int number = convert_number(entry); |
| 73 |
printf("num: %i\n", atoi(num)); |
PRINTPRIME(number); |
|
PRINTPRIME(atoi(num)); |
|
| 74 |
} |
} |
| 75 |
fclose(fp); |
fclose(fp); |
| 76 |
} |
} |