Given a number N, the task is to find units place digit of the first N natural numbers factorials, i.e. 1!+2!+3!+….N! where N<=10e18.
Input: n = 2 Output: 3 1! + 2! = 3 Last digit is 3 Input: n = 3 Output: 9 1! + 2! + 3! = 9 Last digit is 9
Naive Approach: In this approach, simply calculate factorial of each number and find sum of these. Finally get the unit place digit of sum. This will take a lot of time and unnecessary calculations.
Efficient Approach: In this approach, only unit’s digit of N is to be calculated in the range [1, 5], because:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
As 5!=120, and factorial of number greater than 5 have trailing zeros. So, N>=5 doesn’t contribrute in unit place while doing sum.
if (n < 5) ans = (1 ! + 2 ! +..+ n !) % 10; else ans = (1 ! + 2 ! + 3 ! + 4 !) % 10; Note : We know (1! + 2! + 3! + 4!) % 10 = 3 So we always return 3 when n is greater than 4.
Below is the implementation of the efficient approach:
For N = 0 : 1 For N = 1 : 1 For N = 2 : 3 For N = 3 : 9 For N = 4 : 3 For N = 5 : 3 For N = 6 : 3 For N = 7 : 3 For N = 8 : 3 For N = 9 : 3 For N = 10 : 3
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 last two digits of sum of N factorials
- Find sum of factorials in an array
- Sum of integers upto N with given unit digit
- Sum of integers upto N with given unit digit (Set 2)
- Find unit digit of x raised to power y
- Count of N-digit numbers having digit XOR as single digit
- Check if a given number divides the sum of the factorials of its digits
- Minimum number of Factorials whose sum is equal to N
- Sum of factorials of Prime numbers in a Linked list
- Place Value of a given digit in a number
- Largest number less than N with digit sum greater than the digit sum of N
- Minimum count of numbers required with unit digit X that sums up to N
- Count numbers with unit digit k in given range
- Count natural numbers whose factorials are divisible by x but not y
- Numbers whose factorials end with n zeros
- Calculating Factorials using Stirling Approximation
- Trailing number of 0s in product of two factorials
- Queries for the product of first N factorials
- GCD of factorials of two numbers
- Print factorials of a range in right aligned format
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.