funky for loop

Hello,
I am having trouble with a for loop that refuses to stop. i created it to generate the fibonacci problems less that 4 million for project euler, but it goes well beyond that parameter. anything helps. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int fib(int n)
{
  if(1 == n || 2 == n)
  {
      return 1;
  }
  else
  {
      return fib(n-1) + fib(n-2);
  }

}

int main()
{
    for(int i=1; i<4000000; i++) {    
        cout << fib(i) << endl;
    }
    return 0;
}

Last edited on
Well, yeah.

Consider the following line:
 
  return fib(n-1) + fib(n-2);


If n is 3,999,999, you're going to return the sum of fib(3,999,998) and fib(2,999,997). Since fib() is recursive, each of those calls will do the same thing.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Last edited on
thank you
Topic archived. No new replies allowed.