Given a number n, we need to find the last digit in factorial n.
Input : n = 4
Output : 4
4! = 4 * 3 * 2 * 1. = 24. Last digit of 24 is 4.
Input : n = 5
Output : 5
5! = 5*4 * 3 * 2 * 1. = 120. Last digit of 120 is 0.
A Naive Solution is to first compute fact = n!, then return the last digit of the result by doing fact % 10. This solution is inefficient and causes integer overflow for even slightly large value of n.
An Efficient Solution is based on the observation that all factorials after 5 have 0 as last digit.
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
Time Complexity : O(1)
Auxiliary Space : O(1)
Now try below problems
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 the last digit when factorial of A divides factorial of B
- Last digit of a number raised to last digit of N factorial
- Last non-zero digit of a factorial
- First digit in factorial of a number
- Maximum number with same digit factorial product
- Find the remainder when First digit of a number is divided by its Last digit
- Find the next Factorial greater than N
- Find sum of digits in factorial of a number
- Find all factorial numbers less than or equal to n
- Find the last two digits of Factorial of a given Number
- Find GCD of factorial of elements of given array
- Find the length of factorial of a number in any given base
- Find the first natural number whose factorial is divisible by x
- Find maximum power of a number that divides a factorial
- Find the last digit of given series
- Find the Number which contain the digit d
- Find two numbers whose sum is N and does not contain any digit as K
- Find two numbers with sum N such that neither of them contains digit K
- Find the middle digit of a given Number
- Find Last Digit of a^b for Large Numbers
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.