Factorial of Large numbers using Logarithmic identity
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. Examples:
Input: N = 100 Output: 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 Input: N = 50 Output: 30414093201713378043612608166064768844377641568960512000000000000
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 Therefore: Another property is by substituting the value of ln(N!). Below is the implementation of the above approach:
Time Complexity: O(N), where N is the given number.
Space complexity: O(1) since using constant variables