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

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