PDA

View Full Version : C++; fibonacci and GCF.

fBaran
Oct 21, 2005, 07:48 PM
Here is my fib() function:

int fib (int x)
{ int i, count=0;
if (x==1 || x==2) return 1;
for (i=0; i < x; i++)
{
count = (x-1) + (x-2);
}
return count;
}
I've been working on this for a couple of hours now, but I can't get it correctly calculate the numbers. A little help?

Thank you all for your input ::cue rimshot:: !

gammamonk
Oct 21, 2005, 08:16 PM
Are you allowed to use recursion? I'm assuming this is for a class or something.

Here's some code I found in 6 seconds on google.

//
// This file contains the C++ code from Program 3.4 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
//
//
unsigned int Fibonacci (unsigned int n)
{
if (n == 0 || n == 1)
return n;
else
return Fibonacci (n - 1U) + Fibonacci (n - 2U);
}

fBaran
Oct 21, 2005, 08:49 PM
My bad. I should have specified NO recursion (that would be too easy). The old fashion iteration!

HexMonkey
Oct 21, 2005, 11:47 PM
Try this:

int fib (int x)
{
//For the first two terms, return 1
if (x==1 || x==2) return 1;

int i, prev2=1, prev=1, newTerm;
for (i=2; i<x; i++)
{
//Find the next term
newTerm = prev + prev2;
//Update the last two terms
prev2 = prev;
prev = newTerm;
}
return newTerm;
}

g0gie
Oct 22, 2005, 03:07 AM
Cheater!!! do it and learn it!!! A CS degree is coveted!!!

fBaran
Oct 22, 2005, 07:07 AM
Cheater!!! do it and learn it!!! A CS degree is coveted!!!
If you're not going to contribute to my thread, don't post it in.
-------

Thanks a lot HexMonkey, I think what I did wrong is that I didn't sawp anything, so thing just kept getting overwritten. Is that right? Clearly, I don't have any swaps, so it must've been recycling old numbers.

NewbieNerd
Oct 22, 2005, 09:17 AM
No, your program as it stands is just adding up numbers less than x twice for the most part. You are correct in returning 1 if x=1 or x=2, but from that step on you should keep track of variables like last and prev, which will be the last two fib numbers you have found so far.

So in the beginning, last = prev = 1. Then, for the remaining x-2 iterations, you need to make prev = last and last = prev + last (use a temp variable to help you do this). In the end, return last.

colocolo
Oct 22, 2005, 12:19 PM
Cheater!!! do it and learn it!!! A CS degree is coveted!!!

Edit: Sorry, on second thought my comments on how unappropiate this thread is because it is as morally wrong as piracy might be out of place.

I do not have enough information about the situation of the OT to judge him as doing something wrong by asking his homework to be done.

Maybe he really tried hard and has the will to learn after all.

If you happenned to read my post before I edited it, I apologize.