C'
dvanhorn <[email protected]>
| Newsgroups | gmane.org.ballistichelmet.lambda |
|---|---|
| Message-ID | <[email protected]> |
Since we're talking 'bout C... can anyone spot the error in the following
program. It takes one command line argument, n, a positive integer, and
reports if it is prime or not. Works fine for 1,2,3,4 but seems to stop
working after that. As far as I can tell this is a straight forward
translation of Aaron's SML is_prime function into C.
gcc -o prime prime.c ; prime 5
5 is not prime.
-d
#include <stdio.h>
int is_factor(int y, int x) {
((y == 0) || ((x % y) == 0));
}
int is_prime (int x) {
int test = 2;
prime_test:
if (test > x) return 0;
else if ((test == x) || ((2 * test) > x)) return 1;
else if (is_factor(test, x)) return 0;
else {
test++;
goto prime_test;
}
}
void usage () {
printf("Usage: prime n, where n is a positive integer");
}
/* checks if string *str is a number */
int isnum (char *str) {
int result = 1,
i = 0;
for (; str [i]; i++)
if (!strchr ("-0123456789", str [i]))
result = 0;
return result;
}
int main(int argc, char *argv[]) {
if ((argc != 2) || !isnum(argv[1])){
usage();
return 0;
}
int x = atoi(argv[1]);
printf("%d is %sprime.\n", x, (is_prime(x) ? "" : "not "));
return 0;
}