[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: JavaSchools (was Re: Colon Operator: Superfluous Syntax?)
- From: Rici Lake <lua@...>
- Date: Fri, 16 Mar 2007 13:46:23 -0500
Alex Queiroz wrote:Could you
write a C example mimicking the scheme example I gave, without
exploding the stack?
And here it is:
rici@rici-desktop:~/src/fact$ cat fact.c
#include <stdlib.h>
#include <stdio.h>
double fact(int n, double accum) {
if (n <= 1) return accum;
else return fact(n-1, n * accum);
}
int printfact(char **argv, int count) {
if (*argv) {
int n = atoi(*argv);
printf("%d! = %.17g%s\n", n, fact(n, 1), n > 18 ? " (more or less)"
: "");
return printfact(argv + 1, count + 1);
}
else return count;
}
int main (int argc, char **argv) {
printf("%d factorials printed\n", printfact(argv+1, 0));
return 0;
}
rici@rici-desktop:~/src/fact$ gcc -O2 -Wall -o fact fact.c
rici@rici-desktop:~/src/fact$ ./fact 0 1 2 3 4 10 15 20 1000 1000000
10000000
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
10! = 3628800
15! = 1307674368000
20! = 2.43290200817664e+18 (more or less)
1000! = inf (more or less)
1000000! = inf (more or less)
10000000! = inf (more or less)
11 factorials printed