Open In App

Find last digit in factorial

Improve
Improve
Like Article
Like
Save
Share
Report

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.

C++




// C++ program to find last digit in
// factorial n using naive approach
#include <iostream>
using namespace std;
 
int lastDigitFactorial(unsigned int n)
{
    // Base case
    if (n == 0) return 1;
 
    // Calculate the factorial of n
    int fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
 
    // Return the last digit of the factorial
    return fact % 10;
}
 
// Driver code
int main() {
 
  cout<<lastDigitFactorial(6);
  return 0;
}


Java




public class Main {
    public static int lastDigitFactorial(int n) {
        // Base case
        if (n == 0) return 1;
 
        // Calculate the factorial of n
        int fact = 1;
        for (int i = 1; i <= n; i++) {
            fact *= i;
        }
 
        // Return the last digit of the factorial
        return fact % 10;
    }
 
    // Driver code
    public static void main(String[] args) {
        System.out.println(lastDigitFactorial(6));
    }
}


Python3




# Python program to find last digit in
# factorial n using naive approach
 
def last_digit_factorial(n):
    # Base case
    if n == 0:
        return 1
 
    # Calculate the factorial of n
    fact = 1
    for i in range(1, n + 1):
        fact *= i
 
    # Return the last digit of the factorial
    return fact % 10
 
# Driver code
print(last_digit_factorial(6))


C#




using System;
 
public class GFG {
     
    public static int LastDigitFactorial(int n) {
        // Base case
        if (n == 0) return 1;
 
        // Calculate the factorial of n
        int fact = 1;
        for (int i = 1; i <= n; i++) {
            fact *= i;
             
            // To ensure that the factorial value doesn't overflow
            fact = fact % 10;
        }
 
        // Return the last digit of the factorial
        return fact % 10;
    }
 
    // Driver Code
    public static void Main(string[] args) {
        Console.WriteLine(LastDigitFactorial(6));
         
        // This Code Is Contributed By Shubham Tiwari
    }
}


Javascript




// javascript code addition
 
function lastDigitFactorial(n) {
  // Base case
  if (n === 0) return 1;
 
  // Calculate the factorial of n
  let fact = 1;
  for (let i = 1; i <= n; i++) {
    fact *= i;
  }
 
  // Return the last digit of the factorial
  return fact % 10;
}
 
// Driver code
console.log(lastDigitFactorial(6));
 
// The code is contributed by Arushi Goel.


Output

0

Time complexity:

Auxiliary space:

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
…………..

C++




// C++ program to find last digit in
// factorial n.
#include <iostream>
using namespace std;
 
int lastDigitFactorial(unsigned int n)
{
   // Explicitly handle all numbers
   // less than or equal to 4
   if (n == 0) return 1;
   else if (n <= 2) return n;
   else if (n == 3) return 6;
   else if (n == 4) return 4;
   
   // For all numbers greater than 4
   // the last digit is 0
   else return 0;
}
 
int main() {
 
    cout<<lastDigitFactorial(6);
    return 0;
}


Java




// Java program to find last 
// digit in factorial n.
import java.io.*;
import java.util.*;
 
class GFG {
     
static int lastDigitFactorial(int n)
{
     
    // Explicitly handle all numbers
    // less than or equal to 4
    if (n == 0) return 1;
    else if (n <= 2) return n;
    else if (n == 3) return 6;
    else if (n == 4) return 4;
     
    // For all numbers greater than
    // 4 the last digit is 0
    else return 0;
}
 
// Driver code
public static void main(String[] args)
{
    System.out.println(lastDigitFactorial(6));
}
}
 
// This code is contributed by coder001


Python3




# Python3 program to find last digit in
# factorial n.
 
def lastDigitFactorial(n):
     
    # Explicitly handle all numbers
    # less than or equal to 4
    if (n == 0): return 1
    elif (n <= 2): return n
    elif (n == 3): return 6
    elif (n == 4): return 4
     
    # For all numbers greater than 4
    # the last digit is 0
    else: return 0
 
print(lastDigitFactorial(6))
 
# This code is contributed by divyeshrabadiya07


C#




// C# program to find last
// digit in factorial n.
using System;
class GFG{
     
static int lastDigitFactorial(int n)
{
     
    // Explicitly handle all numbers
    // less than or equal to 4
    if (n == 0) return 1;
    else if (n <= 2) return n;
    else if (n == 3) return 6;
    else if (n == 4) return 4;
     
    // For all numbers greater than
    // 4 the last digit is 0
    else return 0;
}
 
// Driver code
public static void Main(string[] args)
{
    Console.Write(lastDigitFactorial(6));
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
// JavaScript program to find last digit in
// factorial n.
 
function lastDigitFactorial(n)
{
    // Explicitly handle all numbers
    // less than or equal to 4
    if (n == 0) return 1;
    else if (n <= 2) return n;
    else if (n == 3) return 6;
    else if (n == 4) return 4;
     
    // For all numbers greater than 4
    // the last digit is 0
    else return 0;
}
 
    // Driver code 
    document.write(lastDigitFactorial(6));
     
// This code is contributed by Surbhi Tyagi
 
</script>


Output

0

Time Complexity: O(1), since no loop is used hence the algorithm takes constant time to execute
Auxiliary Space: O(1), since no extra array is used hence constant space is used

Approach 2: Using Loop:

The current approach works well for small values of n but is not efficient for large values of n. One way to optimize this approach is to compute the last digit of the factorial using modular arithmetic. The last digit of the factorial is the same as the last digit of the product of all the numbers from 1 to n.

Here’s the optimized approach:

C++




#include <iostream>
using namespace std;
 
int lastDigitFactorial(unsigned int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    int lastDigit = 1;
    for (int i = 2; i <= n; i++) {
        lastDigit = (lastDigit * i) % 10;
    }
    return lastDigit;
}
 
int main() {
    cout << lastDigitFactorial(6);
    return 0;
}


Java




public class Main {
    static int lastDigitFactorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        }
        int lastDigit = 1;
        for (int i = 2; i <= n; i++) {
            lastDigit = (lastDigit * i) % 10;
        }
        return lastDigit;
    }
 
    public static void main(String[] args) {
        System.out.println(lastDigitFactorial(6));
    }
}


Python3




def lastDigitFactorial(n):
    if n == 0 or n == 1:
        return 1
    lastDigit = 1
    for i in range(2, n+1):
        lastDigit = (lastDigit * i) % 10
    return lastDigit
 
print(lastDigitFactorial(6))


C#




using System;
 
class Program {
    static int LastDigitFactorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        }
        int lastDigit = 1;
        for (int i = 2; i <= n; i++) {
            lastDigit = (lastDigit * i) % 10;
        }
        return lastDigit;
    }
 
    static void Main(string[] args) {
        Console.WriteLine(LastDigitFactorial(6));
    }
}


Javascript




function lastDigitFactorial(n) {
    if (n == 0 || n == 1) { // if n is 0 or 1, return 1
        return 1;
    }
    let lastDigit = 1; // initialize lastDigit to 1
    for (let i = 2; i <= n; i++)
    {
     
        // loop from 2 to n
        // multiply lastDigit by i and take the last digit
        lastDigit = (lastDigit * i) % 10;
    }
    return lastDigit; // return the last digit of the factorial
}
 
// call the function with n = 6 and log the result to the console
console.log(lastDigitFactorial(6));


Output:

0

Time Complexity: O(N) 
Auxiliary Space: O(1), since no extra array is used hence constant space is used

Now try below problems

1) Last non-zero digit in factorial
2) Count zeroes in factorial
3) First digit in Factorial



Last Updated : 31 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads