You are here:

C++/fibonacci

Advertisement


Question
HI

i've written a nonrecursive fibonacci function and my purpose is to finding the largest fibonacci number that can be printed by my system.
the below code is what i've written,but i don't know what i should write in the while loop,to find the largest number.

Thanx
Bita


#include<iostream>
using std::cout;
using std::cin;
using std::endl;

int fib(int);

int main()
{
  int n=2,i=0;

  while(fib(n)<=1000000010)
  {
     n++;
     cout<<"n : "<<n<<" , "<<"fib : "<<fib(n)<<endl;
  }

  return 0;
}
int fib(int x)
{
  int f=0;
  int f1=0;
  int f2=1;

  if(x==1)
     return f1;
  if(x==2)
     return f2;
  else
  {
     for(int i=1;i<=x-2;i++)
     {
        f = f1 + f2;
        f1 = f2;
        f2 = f;
     }
  }
  return f;
}  

Answer
When there is an integer overflow, the bits overflow into the sign bit of the integer and it becomes negative. As you fib() function is returning an integer, it will return a negative value if there is an integer overflow ie. if the number is too big to be represented in an int as a positive value. So, all you have to do is keep generating fibonacci numbers till you get a negative number.

int main()
{
      int n = 2 ;

      while( fib(n) >= 0 )
      {
         cout << "n : " << n << " , " << "fib : " << fib(n) << '\n' ;
         n ;
      }
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.