"Julian V. Noble" wrote:
> jugaaru wrote:
> >
> > How to generate fibonacci mubers in C ?
>
> The algorithm is
>
> F(n+1) = F(n) + F(n-1) , F(0) = 0, F(1) = 1
>
> You can do this recursively (very stupid and slow--see my article
> "Recurses!" in Computing in Science and Engineering) or iteratively
> (much better).
>
> I won't tell you how to do it since it is evidently homework.
But I will for two reasons: 1. Enough time has passed so that the
homework should have been passed in. 2. If the OP can rework the
following into something the instructor will believe is his, he
will have learned something.
BTW the following shows up a glitch in DJGPP 2.03 system. Calling
the program with an argument of -1 returns the overflow condition,
because strtoul returns ULONG_MAX rather than 0. Cross-posted to
comp.os.msdos.djgpp for this.
#include <stdio.h>
#include <stdlib.h>
/* ------------------ */
/* deliberately written to upset some style mavens */
/* returns ULONG_MAX for overflow */
static unsigned long fibo(unsigned int n)
{
unsigned long pprev, prev, value;
if ((pprev = 0) == n) value = pprev;
else if ((prev = 1) == n) value = prev;
else do {
value = pprev + prev; pprev = prev; prev = value;
if (value < pprev) {
value = -1; /* ULONG_MAX, overflow */
goto x;
}
} while (2 <= --n);
x: return value;
} /* fibo */
/* ------------------ */
int main(int argc, char **argv)
{
unsigned int n;
if (2 != argc) puts("Usage: fibo N");
else {
n = strtoul(argv[1], NULL, 10);
printf("fibonacci(%u) = %lu\n", n, fibo(n));
}
return 0;
} /* main */
--
Chuck F (
[email protected]) (
[email protected])
Available for consulting/temporary embedded and systems.
<
http://cbfalconer.home.att.net> USE worldnet address!