Re: Fibonacci implementation



Christian Christmann wrote:

I'm looking for a non-recursive implementation of the algorithm to
calculate Fibonacci numbers. Any language is OK (C/C++, pseudo code
prefered).

#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 (cbfalconer@xxxxxxxxx) (cbfalconer@xxxxxxxxxxxxx)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE maineline address!


.



Relevant Pages

  • Re: Fibonacci implementation
    ... Christian Christmann said: ... pseudo code ... Any hints? ... int main ...
    (comp.programming)
  • Re: Data flow analysis
    ... On Sun, 14 Jan 2007, Christian Christmann wrote: ... int function// 1 ... or a value previously written into 'x' by the assignment in line 3.) ...
    (comp.programming)
  • Re: Strange function use
    ... Christian Christmann wrote: ... int a, b, foo; ... int a, b, foo(int); ... foooccurs inside a declaration. ...
    (comp.lang.c)
  • Re: Function return type
    ... Christian Christmann wrote: ... C89 defines: main ... C99 defines: int main ... Best is: int main ...
    (comp.lang.c)
  • Re: Implicit declaration
    ... Christian Christmann said: ... int main ... When I compile this file, ... void test(int); ...
    (comp.lang.c)