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
- Find the unit place digit of sum of N factorials
- Find smallest number with given number of digits and sum of digits
- Find the Largest number with given number of digits and sum of digits
- GCD of factorials of two numbers
- Product of first N factorials
- Numbers whose factorials end with n zeros
- Calculating Factorials using Stirling Approximation
- Trailing number of 0s in product of two factorials
- Count natural numbers whose factorials are divisible by x but not y
- Print factorials of a range in right aligned format
- Program to find last two digits of 2^n
- Find first and last digits of a number
- Given a number n, find the first k digits of n^n
- Find a number x such that sum of x and its digits is equal to given n.
- Find the n-th number made of even digits only
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.