/[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.6 - (hide annotations)
Fri May 12 21:13:49 2006 UTC (18 years, 4 months ago) by joko
Branch: MAIN
Changes since 1.5: +22 -7 lines
File MIME type: text/plain
+ added BOOL
+ "convert_number" as a wrapper for "strtol", which should replace "atoi"
+ checking for too large longints

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

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