# Factorial of Large Number Using boost multiprecision in C++

Hello learners, today in this tutorial we will learn how to find the factorial of large numbers in C++ using boost multi-precision library. We can easily find the factorial of smaller numbers like (5!) using normal programs but to find factorial of large numbers like (100!) which results in 158 digits. So it is not possible to store these many digits even if we use unsigned long long int. Let’s understand this in more detail using an easy and comprehensible example.

## Factorial of Large Number Using boost multi-precision library

One way to solve the above problem is to store the result in an array or string by using some logic. Another way is that we can use a boost library which has included the multi-precision library which is used when we need precision more than 64 bits.

Now we will find the factorial using recursion and using for loop.

Here is the code:

**1. Using** **Recursion**

#include <bits/stdc++.h> #include <boost/multiprecision/cpp_int.hpp> namespace mp = boost::multiprecision; using namespace std; mp::cpp_int fact(mp::cpp_int num) { if(num == 1 || num == 0) return 1; else return num * fact(num-1); } int main() { mp::cpp_int num = 100; cout<<fact(num)<<endl; }

Output:

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

2. Using**For Loop **

#include <bits/stdc++.h> #include <boost/multiprecision/cpp_int.hpp> namespace mp = boost::multiprecision; using namespace std; mp::cpp_int fact(mp::cpp_int num) { mp::cpp_int result = 1; for (int i = 1; i <= num; i++) result = result * i; return result; } int main() { mp::cpp_int num = 50; cout<<fact(num)<<endl; }

Output:

30414093201713378043612608166064768844377641568960512000000000000

Note: Make sure that the compiler you are using has the boost multi-precision library.

I hope this article was helpful to you. Keep Coding Keep Learning.

Also Read:

## Leave a Reply