delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2004/02/23/06:16:38

X-Authentication-Warning: delorie.com: mail set sender to djgpp-bounces using -f
Message-ID: <4039DD96.3F36F3B7@yahoo.com>
From: CBFalconer <cbfalconer AT yahoo DOT com>
Organization: Ched Research
X-Mailer: Mozilla 4.75 [en] (Win98; U)
X-Accept-Language: en
MIME-Version: 1.0
Newsgroups: comp.lang.c,comp.os.msdos.djgpp
Subject: Re: Fibonacci number
References: <d7c3a0b2 DOT 0402220759 DOT 34d6435d AT posting DOT google DOT com> <4038E8CA DOT 6491815E AT virginia DOT edu>
Lines: 67
Date: Mon, 23 Feb 2004 11:03:03 GMT
NNTP-Posting-Host: 12.76.139.200
X-Complaints-To: abuse AT worldnet DOT att DOT net
X-Trace: bgtnsc05-news.ops.worldnet.att.net 1077534183 12.76.139.200 (Mon, 23 Feb 2004 11:03:03 GMT)
NNTP-Posting-Date: Mon, 23 Feb 2004 11:03:03 GMT
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

"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 (cbfalconer AT yahoo DOT com) (cbfalconer AT worldnet DOT att DOT net)
   Available for consulting/temporary embedded and systems.
   <http://cbfalconer.home.att.net>  USE worldnet address!

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019