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

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