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
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.
- Check if a given number divides the sum of the factorials of its digits
- Find the unit place digit of sum of N factorials
- Find sum of factorials in an array
- Trailing number of 0s in product of two factorials
- GCD of factorials of two numbers
- Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
- Minimum number of Factorials whose sum is equal to N
- Sum of factorials of Prime numbers in a Linked list
- Program to find last two digits of Nth Fibonacci number
- Program to find last two digits of 2^n
- Program to find the last two digits of x^y
- Find the last two missing digits of the given phone number
- Find the last two digits of Factorial of a given Number
- Minimum digits to be removed to make either all digits or alternating digits same
- Count natural numbers whose factorials are divisible by x but not y
- Numbers whose factorials end with n zeros
- Calculating Factorials using Stirling Approximation
- Queries for the product of first N factorials
- Print factorials of a range in right aligned format
- Product of first N factorials
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.