Given a very large number N, the task is to find the factorial of the number using Log.
Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to N.
We have previously discussed a simple program to find the factorial in this article. Here, we will discuss an efficient way to find the factorial of large numbers.
Input: N = 100
Input: N = 50
Approach: The most common iterative version runs in expected O(N) time. But as numbers become big it will be wrong to assume that multiplication takes constant time. The naive approach takes O(K*M) time for multiplication where K is the length of the multiplier and M is the length of the multiplicand. Therefore, the idea is to use logarithmic properties:
As we know that and
Another property is
by substituting the value of ln(N!).
Below is the implementation of the above approach:
The factorial is: 93326215443944231979346762015249956831505959550546075483971433508015162170687116519232751238036777284091181469944786448222582618323317549251483571058789842944.000000
Time taken: 0.000114 s
Time Complexity: O(N), where N is the given number.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the last digit when factorial of A divides factorial of B
- Factorial of a large number
- Multiply large integers under large modulo
- Significance of Pascal’s Identity
- Cassini’s Identity
- Program for Identity Matrix
- Euler's Four Square Identity
- Brahmagupta Fibonacci Identity
- Proizvolov's Identity
- Multiply Large Numbers using Grid Method
- Subtraction of two large numbers using 9's compliment
- Subtraction of two large numbers using 10's compliment
- Count factorial numbers in a given range
- Find all factorial numbers less than or equal to n
- Expressing factorial n as sum of consecutive numbers
- Check whether factorial of N is divisible by sum of first N natural numbers
- Check if factorial of N is divisible by the sum of squares of first N natural numbers
- GCD of two numbers when one of them can be very large
- Find Last Digit of a^b for Large Numbers
- Remainder with 7 for large numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.