/[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.5 - (hide annotations)
Fri May 12 20:38:15 2006 UTC (18 years, 6 months ago) by joko
Branch: MAIN
Changes since 1.4: +14 -10 lines
File MIME type: text/plain
+ compiles with "-ansi -pedantic"
+ PRINTERROR prints to stderr
+ handles error-case when no arguments given

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

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