473,657 Members | 2,422 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Fibonacci number

How to generate fibonacci mubers in C ?
Nov 14 '05 #1
62 5410
On 22 Feb 2004 07:59:08 -0800, ju*****@yahoo.c om (jugaaru) wrote:
How to generate fibonacci mubers in C ?


At least two ways: iteratively (create an array, and populate it
on-the-fly), or recursively (have a function return 0 and 1 for the first
two Fibonacci numbers, and then have it calculate any other by calling
itself to acquire the previous two. Note that there's a /serious/
performance degradation for the 2nd technique, but it is more fun to code
;-)
-leor
Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #2
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.

Julian V. Noble
Professor Emeritus of Physics
jv*@lessspamfor mother.virginia .edu
^^^^^^^^^^^^^^^ ^^^
http://galileo.phys.virginia.edu/~jvn/

"For there was never yet philosopher that could endure the
toothache patiently."

-- Wm. Shakespeare, Much Ado about Nothing. Act v. Sc. 1.
Nov 14 '05 #3

"jugaaru" <ju*****@yahoo. com> wrote in message
news:d7******** *************** ***@posting.goo gle.com...
How to generate fibonacci mubers in C ?


#include <stdio.h>

int main() {

printf("fibonac ci mubers in C\n");
return 0;
}

Nov 14 '05 #4

jugaaru wrote:
How to generate fibonacci mubers in C ?


http://en.wikipedia.org/wiki/Fibonacci_number

Save the root of that link, it is a nice one to have handy for all sorts of
questions.
Nov 14 '05 #5
jugaaru wrote:
How to generate fibonacci mubers in C ?


Since it is definately a hw, I do not think that anyone should give you
an answer - the only way to learn is to get your feet wet..

But consider the following:

1) In the recursive solution, the resulting code is really trivial and
small (hint: the smallest possible is 3 lines).. Perfomance is missing
though...

2) Prefer the iterative solution, although it may seem a bit more
complicated..
When I was given the exercise, I had also to optimize my code for many
calls to the fibonacci procedure..
I used a static array to hold already calculated fibonacci numbers, to
speed up execution...
That is, the first time you calculate the 10th number, the array was
filled with some of the previous numbers.. Now, if you have to calculate
the 20th number, you don't need to do it all over again... Calculating
the 5th number is tricky though ;)...

3) I think I said enough already...

--
#include <stdio.h>
#define p(s) printf(#s" endian")
int main(void){int v=1;*(char*)&v? p(Little):p(Big );return 0;}

Giannis Papadopoulos
http://dop.users.uth.gr/
University of Thessaly
Computer & Communications Engineering dept.
Nov 14 '05 #6
In article <8i************ *************** *****@4ax.com> Leor Zolman <le**@bdsoft.co m> writes:
On 22 Feb 2004 07:59:08 -0800, ju*****@yahoo.c om (jugaaru) wrote:
How to generate fibonacci mubers in C ?


At least two ways: iteratively (create an array, and populate it
on-the-fly), or recursively (have a function return 0 and 1 for the first
two Fibonacci numbers, and then have it calculate any other by calling
itself to acquire the previous two.


I prefer the direct, third, method. But you must not forget to include
math.h in that case (for the pow function). Moreover, it will not be
accurate when you wish use 64-bit integers.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 14 '05 #7
Papadopoulos Giannis <ip******@inf.u th.gr> wrote in message news:<c1******* ****@ulysses.no c.ntua.gr>...
jugaaru wrote:
How to generate fibonacci mubers in C ?


Since it is definately a hw, I do not think that anyone should give you
an answer - the only way to learn is to get your feet wet..

But consider the following:

1) In the recursive solution, the resulting code is really trivial and
small (hint: the smallest possible is 3 lines).. Perfomance is missing
though...

2) Prefer the iterative solution, although it may seem a bit more
complicated..
When I was given the exercise, I had also to optimize my code for many
calls to the fibonacci procedure..
I used a static array to hold already calculated fibonacci numbers, to
speed up execution...
That is, the first time you calculate the 10th number, the array was
filled with some of the previous numbers.. Now, if you have to calculate
the 20th number, you don't need to do it all over again... Calculating
the 5th number is tricky though ;)...

3) I think I said enough already...

--
#include <stdio.h>
#define p(s) printf(#s" endian")
int main(void){int v=1;*(char*)&v? p(Little):p(Big );return 0;}

Giannis Papadopoulos
http://dop.users.uth.gr/
University of Thessaly
Computer & Communications Engineering dept.


--------------------
Yeah you are right, this is a Homework. I have just started learning
C, I am having trouble learning it. First 2-3 chapters, i can
understand variables,equat ion, somethings like maths. But when the
faculty start giving assignment. You have no clue how to do it.
Please advise how do i learn C programming.
Nov 14 '05 #8
jugaaru writes:
Yeah you are right, this is a Homework. I have just started learning
C, I am having trouble learning it. First 2-3 chapters, i can
understand variables,equat ion, somethings like maths. But when the
faculty start giving assignment. You have no clue how to do it.
Please advise how do i learn C programming.


Using the link I provided can you write a function to return F(0)? F(1)?
F(2)? F(3)? Do this with pencil and paper. Now try the other way,
starting with F(3) and working down. Then generalize the method you
discover and write a program to automate the process.

Perhaps you will be more comfortable with this alternative assignment:
Write a program to print the first ten Fibonacci numbers. Do that first,
throw it away, and then do the assigned problem. That essentially divides
the problem into two simpler problems.
Nov 14 '05 #9
"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.d jgpp 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("fibonac ci(%u) = %lu\n", n, fibo(n));
}
return 0;
} /* main */

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!

Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
13101
by: dleecurt | last post by:
Hello, I have a small problem, I am trying to write a program that will calculate the Fibonacci number series, and I have the code complete with one problem. I used a long in to store the numbers, and when the numbers get too large it maxes out the int and I can't count any higher. I am trying to use extremely large numbers, I would like to use up to 10^50 or so. So my question is how do I do this? I'm just learning the language and I...
5
7736
by: Niks | last post by:
Can anybody explain me what is a "Fibonacci search"? even an URL will do. Thanks for reading.
4
4849
by: YS Sze | last post by:
If you know the exact longitude and latitude for a specific location, would anyone think it'd make any sense to find out if this set of location numbers is really part of the Fibonacci series or not? Or, another way to look at this is that: Would anyone of you think it is worth a while to find out if there is any location on earth with the set of longitude and latitude numbers that coincides with the Fibonacci series? As I see it, if...
14
4934
by: felixnielsen | last post by:
Im actually kinda embarassed to ask this question... @code start #include <iostream> int main() { unsigned long long a = 1; unsigned long long b = 1; for (int i = 0; i < 45; i++) { a += b; std::cout << a/b << std::endl;
12
1897
by: Santosh Krisnan | last post by:
hello all, I fiddled with BASIC in the early 90s but left it at that. Now I am trying to learn C. I tried to solve an exercise in my book, but it failes to compile. Can anyone tell me what the error messages mean & what I should do? thanks.
13
3165
by: mac | last post by:
Hi, I'm trying to write a fibonacci recursive function that will return the fibonacci string separated by comma. The problem sounds like this: ------------- Write a recursive function that creates a character string containing the first n Fibonacci numbers - F(n) = F(n - 1) + F(n - 2), F(0) = F(1) = 1 -, separated by comma. n should be given as an argument to the program. The recursive function should only take one parameter, n, and...
6
4971
by: Andrew Tatum | last post by:
I'm having some problems with the below equation. I have no problems when it comes to positives. Negatives create the problem.. C 2 1 4 However, this doesn't work:
7
1990
by: ssecorp | last post by:
I am not clear about the results here. from timeit import Timer import Decorators def fib(n): a, b = 1, 0 while n: a, b, n = b, a+b, n-1
1
8829
by: altaey | last post by:
Question Details: Write a program to find and print a Fibonacci sequence of numbers. The Fibonacci sequence is defined as follow: Fn = Fn-2 + Fn-1, n >= 0 F0 = 0, F1 = 1, F2 = 1 Your program should prompt the user to enter a limit and indicate whether the last number in the sequence printed is either even or odd.
0
8323
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8838
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8613
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7351
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5638
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2740
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.