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
- Find unit digit of x raised to power y
- Sum of integers upto N with given unit digit (Set 2)
- Sum of integers upto N with given unit digit
- Count numbers with unit digit k in given range
- Find last two digits of sum of N factorials
- Find sum of factorials in an array
- Find the remainder when First digit of a number is divided by its Last digit
- Find the last digit of given series
- Find the Number which contain the digit d
- Program to find the last digit of X in base Y
- Find Last Digit of a^b for Large Numbers
- Find nth number that contains the digit k or divisible by k.
- Find the occurrences of digit d in the range [0..n]
- Find the Nth digit in the proper fraction of two numbers
- Program to find last digit of n'th Fibonnaci 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.