1 |
joko |
1.7 |
/* $Id: prime.c,v 1.6 2006/05/12 21:13:49 joko Exp $ */ |
2 |
joko |
1.5 |
|
3 |
joko |
1.1 |
#include <stdio.h> |
4 |
joko |
1.6 |
#include <stdlib.h> |
5 |
|
|
#include <limits.h> |
6 |
joko |
1.3 |
|
7 |
joko |
1.6 |
#define BOOL int |
8 |
|
|
#define TRUE 1 |
9 |
|
|
#define FALSE 0 |
10 |
|
|
|
11 |
|
|
#define PRINTPRIME(x) if (is_prime(x)) printf("%i\n", x) |
12 |
joko |
1.5 |
#define PRINTERROR(message) fprintf(stderr, "ERROR: %s\n", message) |
13 |
joko |
1.4 |
|
14 |
joko |
1.5 |
/* check for prime number */ |
15 |
joko |
1.6 |
BOOL is_prime(long int number) |
16 |
joko |
1.1 |
{ |
17 |
joko |
1.4 |
int i; |
18 |
joko |
1.7 |
|
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 |
joko |
1.4 |
for (i=2; i*i <= number; i++) { |
24 |
|
|
if ((number % i) == 0) |
25 |
joko |
1.6 |
return FALSE; |
26 |
|
|
} |
27 |
|
|
return TRUE; |
28 |
|
|
} |
29 |
|
|
|
30 |
joko |
1.7 |
/* convert from string to long int, with error checking */ |
31 |
joko |
1.6 |
long int convert_number(const char *nptr) { |
32 |
|
|
long int number = strtol(nptr, (char **)NULL, 10); |
33 |
joko |
1.7 |
if (number == LONG_MAX || number == LONG_MIN) { |
34 |
|
|
char message[254]; |
35 |
|
|
snprintf(message, 255, "Number is not in range of 'long int': %s", nptr); |
36 |
|
|
PRINTERROR(message); |
37 |
|
|
exit(-1); |
38 |
joko |
1.4 |
} |
39 |
joko |
1.1 |
} |
40 |
joko |
1.3 |
|
41 |
joko |
1.1 |
int main(int argc, char * argv[]) |
42 |
|
|
{ |
43 |
joko |
1.4 |
|
44 |
|
|
if (argc == 1) { |
45 |
joko |
1.6 |
PRINTERROR("No arguments given."); |
46 |
joko |
1.7 |
exit(-1); |
47 |
joko |
1.4 |
} |
48 |
|
|
|
49 |
joko |
1.5 |
/* (3) range mode */ |
50 |
joko |
1.4 |
if (argc > 2) { |
51 |
joko |
1.7 |
long int i, j; |
52 |
|
|
j = convert_number(argv[2]); |
53 |
|
|
for (i = convert_number(argv[1]); i< j; i++) { |
54 |
joko |
1.1 |
PRINTPRIME(i); |
55 |
|
|
} |
56 |
joko |
1.4 |
|
57 |
joko |
1.5 |
/* other modes */ |
58 |
joko |
1.4 |
} else { |
59 |
|
|
|
60 |
joko |
1.5 |
/* try to open file for reading */ |
61 |
joko |
1.4 |
FILE * fp = fopen(argv[1], "r"); |
62 |
|
|
|
63 |
joko |
1.5 |
/* (1) test-single-number mode: first argument is not a filename */ |
64 |
joko |
1.4 |
if (fp == NULL) { |
65 |
joko |
1.7 |
long int number = convert_number(argv[1]); |
66 |
|
|
PRINTPRIME(number); |
67 |
joko |
1.4 |
|
68 |
joko |
1.5 |
/* (2) file mode: read numbers from file */ |
69 |
joko |
1.4 |
} else { |
70 |
joko |
1.7 |
char entry[11]; |
71 |
|
|
while (fgets(entry, 11, fp)) { |
72 |
|
|
long int number = convert_number(entry); |
73 |
|
|
PRINTPRIME(number); |
74 |
joko |
1.5 |
} |
75 |
joko |
1.1 |
fclose(fp); |
76 |
|
|
} |
77 |
|
|
} |
78 |
|
|
} |