Large Fibonacci numbers

  algorithm, c++, fibonacci

I am trying to calculate the elements of Fibonacci sequence , I am sure that the algorithm I used is good and do it job but I am facing a problem when it comes to a large elements like the 100th element or the 200th element , The code calculate the element but the result is wrong .
I used double and long double data type and the code still give me wrong answers for huge numbers .
Here is the code :

#include<iostream>
   #include<string>
   using namespace std ;
   int main()
   {
       int n ;
       long double first , second ,current ;
       while(cin>>n)
       {
           first = 0 ;
           second = 1 ;
           if(n==0)
               cout<<0<<endl ;
           if(n==1)
               cout<<1<<endl ;
           else
           {
               for(int i = 2 ; i<=n ; i++)
               {
                   current = first + second ;
                   first = second ;
                   second = current ;
               }
               string digit = to_string(current) ;
               for(int i = 0 ; i<digit.size() ; i++)
               {
                   if(digit[i]=='.')
                       break ;
                   cout<<digit[i] ;
               }
               cout<<endl ;
           }
       }
       return 0 ;
   }

Wish that you help me .

Source: Windows Questions C++

LEAVE A COMMENT