/[cvs]/joko/Uni/BSArch/01/prime.c
ViewVC logotype

Annotation of /joko/Uni/BSArch/01/prime.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.4 - (hide annotations)
Fri May 12 19:53:48 2006 UTC (18 years, 4 months ago) by joko
Branch: MAIN
Changes since 1.3: +37 -19 lines
File MIME type: text/plain
+ comments
+ makro: PRINTERROR
+ layout changes

1 joko 1.1 #include <stdio.h>
2 joko 1.3
3 joko 1.4 #define PRINTPRIME(x) if(is_prime(x)) printf("%i\n", x)
4     #define PRINTERROR(message) printf("ERROR: %s\n", message)
5    
6     // check for prime number
7     int is_prime(int number)
8 joko 1.1 {
9 joko 1.4 int i;
10     for (i=2; i*i <= number; i++) {
11     if ((number % i) == 0)
12     return 0;
13     }
14     return 1;
15 joko 1.1 }
16 joko 1.3
17 joko 1.1 int main(int argc, char * argv[])
18     {
19 joko 1.4
20     // TODO: segfaults if zero arguments given
21     // switch/case???
22     if (argc == 1) {
23     PRINTERROR("No arguments given, will segfault under cygwin. :-)");
24     }
25    
26     // (3) range mode
27     if (argc > 2) {
28     int i, j;
29     j = atoi(argv[2]);
30     for (i = atoi(argv[1]); i< j; i++) {
31 joko 1.1 PRINTPRIME(i);
32     }
33 joko 1.4
34     // other modes
35     } else {
36    
37     // try to open file for reading
38     FILE * fp = fopen(argv[1], "r");
39    
40     // (1) test-single-number mode: first argument is not a filename
41     if (fp == NULL) {
42 joko 1.1 PRINTPRIME(atoi(argv[1]));
43 joko 1.4
44     // (2) file mode: read numbers from file
45     } else {
46     char num[11];
47     while (fgets(num, 11, fp))
48 joko 1.1 PRINTPRIME(atoi(num));
49     fclose(fp);
50     }
51     }
52     }

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed