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