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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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 the last two digits of Factorial of a given Number
- Find all factorial numbers less than or equal to n
- Find sum of digits in factorial of a 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 two numbers with sum N such that neither of them contains digit K
- Find the Number which contain the digit d
- Find nth number that contains the digit k or divisible by k.
- Find the largest N digit multiple of N
- 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 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.