A common experience, I assure you.

Printable View

- 10-21-2011CommonTater
- 10-21-2011rmatze
- 10-21-2011manasij7479
- 10-21-2011iGuardian
I assume I made the same mistake as before. Is this in the right direction?

Code:`#include <iostream>`

using namespace std;

int fib ( int n );

// Function reference.

int main()

{

int sum_of_all_fibs = 0;

// The sum will begin at zero, this will be the final output of all numbers

// found to be modded by 5 or 3 and be less then 4,000,000.

do

{

int n = 1;

fib (n) == fib (++n);

if (fib(n) % 3 == 0 || fib(n) % 5 == 0)

{

sum_of_all_fibs += fib(n);

}

}

while ( sum_of_all_fibs < 4000000 );

}

int fib ( int n )

{

int fib = 0;

int fib1 = 0;

int fib2 = 1;

int sum_of_all_fibs;

fib = fib1 + fib2;

fib1 = fib2;

fib2 = sum_of_all_fibs;

return sum_of_all_fibs;

}

- 10-21-2011iMalc
To be honest, I wouldn't use a function for the fibonacci number here. At any given point during your loop you have the two previous fibonacci numbers and the next one is equal to their sum. Then it's a matter of shifting the previous one back into the previous previous variable, and moving the next one into the previous variable, ready for the next time around the loop.

Then get your if statement in the right place, test the right variable, and loop up until the right ending condition.

A recursive fibonacci function isn't just inefficient, it's diabolically inefficient at roughly O(2^(0.694n)). Even a value around 200 would take somewhere on the order of as much time as the age of the universe to calculate, on the worlds fastest PC. It simply cannot be used for this.

The first thing that comes mind which is worse than that is Ackermann's function, which is saying a lot