Given a number N, the task is to find unit and tens places digit of the first N natural numbers factorials, i.e last last two digit of 1!+2!+3!+….N! where N<=10e18.
Input : n = 2 Output :3 1! + 2! = 3 Last two digit is 3 Input :4 Output :33 1!+2!+3!+4!=33 Last two digit is 33
Naive Approach:In this approach, simply calculate factorial of each number and find sum of these. Finally get the unit and tens place digit of sum. This will take a lot of time and unnecessary calculations.
Efficient Approach: In this approach, only unit’s and ten’s digit of N is to be calculated in the range [1, 10], because:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
As 10 != 3628800, and factorial of number greater than 10 have two trailing zeros. So, N>=10 doesn’t contribute in unit and tens place while doing sum.
if (n < 10)
ans = (1 ! + 2 ! +..+ n !) % 100;
ans = (1 ! + 2 ! + 3 ! + 4 !+ 5 ! + 6 ! + 7 ! + 8 ! + 9 ! + 10 !) % 100;
Note : We know (1! + 2! + 3! + 4!+…+10!) % 100 = 13
So we always return 3 when n is greater
Below is the implementation of above approach.
For N = 1 : 1 For N = 2 : 3 For N = 3 : 9 For N = 4 : 33 For N = 5 : 53 For N = 6 : 73 For N = 7 : 13 For N = 8 : 33 For N = 9 : 13 For N = 10 : 13
- Check if a given number divides the sum of the factorials of its digits
- Find sum of factorials in an array
- Find the unit place digit of sum of N factorials
- Find the average of k digits from the beginning and l digits from the end of the given number
- Find the Largest number with given number of digits and sum of digits
- Find smallest number with given number of digits and sum of digits
- Product of first N factorials
- GCD of factorials of two numbers
- Numbers whose factorials end with n zeros
- Trailing number of 0s in product of two factorials
- Calculating Factorials using Stirling Approximation
- Program to find last two digits of 2^n
- Program to find the last two digits of x^y
- Given a number n, find the first k digits of n^n
- Find first and last digits of a number
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.