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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.4 - (show 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 #include <stdio.h>
2
3 #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 {
9 int i;
10 for (i=2; i*i <= number; i++) {
11 if ((number % i) == 0)
12 return 0;
13 }
14 return 1;
15 }
16
17 int main(int argc, char * argv[])
18 {
19
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 PRINTPRIME(i);
32 }
33
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 PRINTPRIME(atoi(argv[1]));
43
44 // (2) file mode: read numbers from file
45 } else {
46 char num[11];
47 while (fgets(num, 11, fp))
48 PRINTPRIME(atoi(num));
49 fclose(fp);
50 }
51 }
52 }

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