Generating large Fibonacci numbers using boost library

In our previous post on fibonacci series, we have seen many approaches to generate fibonacci numbers. In this approach, we shall be generating fibonacci numbers with the help of boost library. The program simply uses the “boost/multiprecision/cpp_int.hpp” boost library in which big_int is defined. The fibonacci numbers beyond the range of long long int can also be generated using the boost library. Below is the C++ implementation to generate fibonacci numbers using the boost library.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to generate large
// number of fibonacci series using the 
// boost multiprecision library
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using big_int = boost::multiprecision::cpp_int;
using namespace std;
  
// function to generate first n
// fibonacci numbers
int fib(unsigned int n)
{
    // seed values
    // 0th and 1st number of the
    // series are 0 and 1
    big_int a = 0;
    big_int b = 1;
    cout << "Term 1 is : " << a << endl; 
    cout << "Term 2 is : " << b << endl;
      
    for (unsigned int i = 2; i < n; ++i)
    {
        const big_int c = a + b;
        cout << "Term "<< i + 1 << " is : " << c << endl;
        a = b;
        b = c;
    }
}
  
// Driver code
int main()
{
    unsigned int n = 30;
      
    // function calling
    fib(n);
      
    return 0;
}

chevron_right


Output :

Term 1 is : 0
Term 2 is : 1
Term 3 is : 1
Term 4 is : 2
Term 5 is : 3
Term 6 is : 5
Term 7 is : 8
Term 8 is : 13
Term 9 is : 21
Term 10 is : 34
Term 11 is : 55
Term 12 is : 89
Term 13 is : 144
Term 14 is : 233
Term 15 is : 377
Term 16 is : 610
Term 17 is : 987
Term 18 is : 1597
Term 19 is : 2584
Term 20 is : 4181
Term 21 is : 6765
Term 22 is : 10946
Term 23 is : 17711
Term 24 is : 28657
Term 25 is : 46368
Term 26 is : 75025
Term 27 is : 121393
Term 28 is : 196418
Term 29 is : 317811
Term 30 is : 514229
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.