Open In App

Find the last two digits of Factorial of a given Number

Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N, the task is to find the last two digits of factorial of a number
Examples: 

Input: N = 7 
Output: 40 
Explanation: 7! = 5040
Input: N = 11 
Output: 00 

Approach#1

We can observe that for N >= 10, the last two places of its factorial will contain 0’s only. Hence N! % 100 for any N >= 10 will always be 0. So we just calculate the factorial if N < 10 and extract the final two digits. 
Below is the implementation of the above approach:

C++




// C++ implementation to
// find last two digits
// factorial of a given number
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the
// last two digits of N!
void lastTwoDigits(long long N)
{
 
    // For N >= 10, N! % 100
    // will always be 0
    if (N >= 10) {
        cout << "00";
        return;
    }
 
    long long fac = 1;
    // Calculating N! % 100
    for (int i = 1; i <= N; i++)
        fac = (fac * i) % 100;
 
    cout << fac;
}
 
// Driver code
int main()
{
    int N = 7;
    lastTwoDigits(N);
}


Java




// Java implementation to
// find last two digits
// factorial of a given number
import java.util.*;
class GFG{
 
// Function to print the
// last two digits of N!
static void lastTwoDigits(double N)
{
 
    // For N >= 10, N! % 100
    // will always be 0
    if (N >= 10)
    {
        System.out.print("00");
        return;
    }
 
    double fac = 1;
     
    // Calculating N! % 100
    for (int i = 1; i <= N; i++)
        fac = (fac * i) % 100;
 
    System.out.print(fac);
}
 
// Driver code
public static void main(String args[])
{
    int N = 7;
    lastTwoDigits(N);
}
}
 
// This code is contributed by Code_Mech


Python3




# Python3 implementation to
# find last two digits
# factorial of a given number
 
# Function to print the
# last two digits of N!
def lastTwoDigits(N):
 
    # For N >= 10, N! % 100
    # will always be 0
    if (N >= 10):
        print("00", end = "")
        return
 
    fac = 1
     
    # Calculating N! % 100
    for i in range(1, N + 1):
        fac = (fac * i) % 100
 
    print(fac)
 
# Driver code
if __name__ == '__main__':
    N = 7
    lastTwoDigits(N)
 
# This code is contributed by Mohit Kumar


C#




// C# implementation to
// find last two digits
// factorial of a given number
using System;
class GFG{
 
// Function to print the
// last two digits of N!
static void lastTwoDigits(double N)
{
 
    // For N >= 10, N! % 100
    // will always be 0
    if (N >= 10)
    {
        Console.Write("00");
        return;
    }
 
    double fac = 1;
     
    // Calculating N! % 100
    for (int i = 1; i <= N; i++)
        fac = (fac * i) % 100;
 
    Console.Write(fac);
}
 
// Driver code
public static void Main()
{
    int N = 7;
    lastTwoDigits(N);
}
}
 
// This code is contributed by Nidhi_biet


Javascript




<script>
 
// JavaScript implementation to
// find last two digits of
// factorial of a given number
 
// Function to print the
// last two digits of N!
function lastTwoDigits(N)
{
 
    // For N >= 10, N! % 100
    // will always be 0
    if (N >= 10) {
        cout << "00";
        return;
    }
 
    let fac = 1;
    // Calculating N! % 100
    for (let i = 1; i <= N; i++)
        fac = (fac * i) % 100;
 
    document.write(fac);
}
 
// Driver code
    let N = 7;
    lastTwoDigits(N);
 
 
// This code is contributed by Surbhi Tyagi.
 
</script>


Output

40

Time complexity: O(n) since using a for loop
Auxiliary space: O(1) because it is using constant space

Approach#2: using slicing and math

This approach uses the math library in Python to calculate the factorial of the input number n. The factorial result is converted to a string and the last two digits are extracted using slicing. Finally, the last two digits are returned in reverse order to get the correct result.

Algorithm

1. Calculate the factorial of the input number n using the math.factorial() function.
2. Convert the result to a string and reverse it.
3. Extract the last two characters using slicing.
4. Reverse the extracted last two characters and return them as a string.

C++




#include <iostream>
#include <cmath>
 
// Function to calculate the last two digits of the factorial of a number
std::string lastTwoDigitsFactorial(int n) {
    // Calculate the factorial of n
    long long factorial = 1;
    for (int i = 1; i <= n; i++) {
        factorial *= i;
    }
 
    // Convert the factorial to a string
    std::string factorialStr = std::to_string(factorial);
 
    // Reverse the string
    std::string reversedStr = "";
    for (int i = factorialStr.length() - 1; i >= 0; i--) {
        reversedStr += factorialStr[i];
    }
 
    // Extract the last two digits
    std::string lastTwoDigits = reversedStr.substr(0, 2);
 
    // Reverse the last two digits to get the correct order
    std::string result = "";
    for (int i = 1; i >= 0; i--) {
        result += lastTwoDigits[i];
    }
 
    return result;
}
 
int main() {
    int n1 = 7;
    int n2 = 11;
 
    // Calculate and print the last two digits of the factorial for n1 and n2
    std::string result1 = lastTwoDigitsFactorial(n1);
    std::string result2 = lastTwoDigitsFactorial(n2);
 
    std::cout << "Last two digits of " << n1 << "! : " << result1 << std::endl;
    std::cout << "Last two digits of " << n2 << "! : " << result2 << std::endl;
 
    return 0;
}


Java




// Java Code for the above approach
import java.util.*;
 
public class GFG {
    // Function to calculate the last two digits of the
    // factorial of a number
    static String lastTwoDigitsFactorial(int n)
    {
        // Calculate the factorial of n
        long factorial = 1;
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
 
        // Convert the factorial to a string
        String factorialStr = Long.toString(factorial);
 
        // Reverse the string
        StringBuilder reversedStr = new StringBuilder();
        for (int i = factorialStr.length() - 1; i >= 0;
             i--) {
            reversedStr.append(factorialStr.charAt(i));
        }
 
        // Extract the last two digits
        String lastTwoDigits = reversedStr.substring(0, 2);
 
        // Reverse the last two digits to get the correct
        // order
        StringBuilder result = new StringBuilder();
        for (int i = 1; i >= 0; i--) {
            result.append(lastTwoDigits.charAt(i));
        }
 
        return result.toString();
    }
 
    public static void main(String[] args)
    {
        int n1 = 7;
        int n2 = 11;
 
        // Calculate and print the last two digits of the
        // factorial for n1 and n2
        String result1 = lastTwoDigitsFactorial(n1);
        String result2 = lastTwoDigitsFactorial(n2);
 
        System.out.println("Last two digits of " + n1
                           + "! : " + result1);
        System.out.println("Last two digits of " + n2
                           + "! : " + result2);
    }
}
 
// This code is contributed by Susobhan Akhuli


Python3




import math
def last_two_digits_factorial(n):
    factorial = str(math.factorial(n))
    z=factorial[::-1]
    last_two_digits = z[:2]
    return last_two_digits[::-1]
print(last_two_digits_factorial(7))
print(last_two_digits_factorial(11))


C#




using System;
 
class Program
{
    // Function to calculate the last two digits of the factorial of a number
    static string LastTwoDigitsFactorial(int n)
    {
        // Calculate the factorial of n
        long factorial = 1;
        for (int i = 1; i <= n; i++)
        {
            factorial *= i;
        }
 
        // Convert the factorial to a string
        string factorialStr = factorial.ToString();
 
        // Reverse the string
        char[] reversedArray = factorialStr.ToCharArray();
        Array.Reverse(reversedArray);
        string reversedStr = new string(reversedArray);
 
        // Extract the last two digits
        string lastTwoDigits = reversedStr.Substring(0, 2);
 
        // Reverse the last two digits to get the correct order
        char[] resultArray = lastTwoDigits.ToCharArray();
        Array.Reverse(resultArray);
        string result = new string(resultArray);
 
        return result;
    }
 
    static void Main()
    {
        int n1 = 7;
        int n2 = 11;
 
        // Calculate and print the last two digits of the factorial for n1 and n2
        string result1 = LastTwoDigitsFactorial(n1);
        string result2 = LastTwoDigitsFactorial(n2);
 
        Console.WriteLine("Last two digits of " + n1 + "! : " + result1);
        Console.WriteLine("Last two digits of " + n2 + "! : " + result2);
    }
}


Javascript




function GFG(n) {
    // Calculate the factorial of n
    let factorial = BigInt(1);
    for (let i = 1; i <= n; i++) {
        factorial *= BigInt(i);
    }
    // Convert the factorial to a string
    let factorialStr = factorial.toString();
    // Reverse the string to get
    // the last two digits
    let reversedStr = factorialStr.split('').reverse().join('');
    // Extract the last two digits
    let lastTwoDigits = reversedStr.slice(0, 2);
    // Reverse again to get the correct order
    return lastTwoDigits.split('').reverse().join('');
}
// Test cases
console.log(GFG(7));
console.log(GFG(11));


Output

Last two digits of 7! : 40
Last two digits of 11! : 00


Time complexity: The time complexity of this program is O(n) as it calculates the factorial using the math.factorial() function which takes O(n) time.
Space complexity: The space complexity of this program is O(n) as it creates a string of length n to store the factorial result.

Approach#3: Using reduce + lambda

This approach uses in this code is to create a lambda function that takes a positive integer as input, and uses the reduce() function from the functools module to calculate the factorial of the input number modulo 100. The reduce() function takes an anonymous function as its first argument that multiplies the accumulator (x) by the next element in the range (y), and returns the result modulo 100. The range starts from 1 and goes up to n+1, where n is the input integer. The initial value of the accumulator is set to 1, since any number multiplied by 1 equals that number.

Algorithm

1. Import the reduce() function from the functools module
2. Initialize a positive integer N
3. Create a lambda function called “last_two_digits” that takes an integer argument n
4. In the lambda function, use the reduce() function to calculate the factorial of n modulo 100
5. The reduce() function takes an anonymous function that multiplies the accumulator by the next element in the range, and returns the result modulo 100
6. The range starts from 1 and goes up to n+1
7. The initial value of the accumulator is set to 1
8. Call the lambda function with N as an argument
9. Print the result as a string formatted to two digits using the “{:02d}” format specifier

C++




// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int N = 11;
 
    // Lambda function to calculate the last two digits of
    // the factorial
    auto last_two_digits = [](int n) {
        int result = 1;
        for (int i = 1; i <= n; i++) {
            result
                = (result * i)
                  % 100; // Calculate the product modulo 100
        }
        return result;
    };
 
    // Calculate the last two digits of N!
    int result = last_two_digits(N);
 
    // Print the result with 2 digits, filled with leading
    // zeros if necessary
    cout << setfill('0') << setw(2) << result << endl;
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Java




// Java program for the above approach
import java.util.function.Function;
 
public class GFG {
 
    public static void main(String[] args)
    {
        int N = 11;
 
        // Lambda function to calculate the last two digits
        // of the factorial
        Function<Integer, Integer> lastTwoDigits = n ->
        {
            int result = 1;
            for (int i = 1; i <= n; i++) {
                result = (result * i)
                         % 100; // Calculate the product
                                // modulo 100
            }
            return result;
        };
 
        // Calculate the last two digits of N!
        int result = lastTwoDigits.apply(N);
 
        // Print the result with 2 digits, filled with
        // leading zeros if necessary
        System.out.printf("%02d%n", result);
    }
}
 
// This code is contributed by Susobhan Akhuli


Python3




from functools import reduce
 
N = 11
 
last_two_digits = lambda n: reduce(lambda x, y: (x*y) % 100, range(1, n+1), 1)
 
print("{:02d}".format(last_two_digits(N)))


C#




using System;
 
class Program
{
    static void Main()
    {
        int N = 11;
 
        // Lambda function to calculate the last two digits of
        // the factorial
        Func<int, int> lastTwoDigits = n =>
        {
            int resultFactorial = 1;
            for (int i = 1; i <= n; i++)
            {
                resultFactorial = (resultFactorial * i) % 100; // Calculate the product modulo 100
            }
            return resultFactorial;
        };
 
        // Calculate the last two digits of N!
        int result = lastTwoDigits(N);
 
        // Print the result with 2 digits, filled with leading
        // zeros if necessary
        Console.WriteLine(result.ToString("D2"));
    }
}


Javascript




// Javascript program for the above approach
// Function to calculate the last two digits of the factorial
let lastTwoDigits = (n) => {
    let result = 1;
    for (let i = 1; i <= n; i++) {
        result = (result * i) % 100; // Calculate the product modulo 100
    }
    return result;
};
 
// Given number
let N = 11;
 
// Calculate the last two digits of N!
let result = lastTwoDigits(N);
 
// Convert the result to a string and pad with leading zeros if necessary
let resultString = result.toString().padStart(2, '0');
 
// Print the result
console.log(resultString);
 
// This code is contributed by Susobhan Akhuli


Output

00


Time Complexity: O(N), where N is the input integer. This is because the reduce() function iterates over the range from 1 to N+1, which takes O(N) time.

Auxiliary Space: O(1), since only a constant amount of memory is used to store the input integer, the lambda function, and the result. The reduce() function only stores the accumulator and the next element in the range at any given time, so the memory usage does not depend on the size of the input integer.

Approach#4: Using a dynamic programming approach:

  1. Start with the input value n passed to the function.
  2. Create an empty list called dp to store the computed factorials.
  3. Append the value 1 to the dp list as the factorial of 0 is 1.
  4. Enter a loop that iterates from 1 to n (inclusive) using the variable i.
  5. Inside the loop, compute the factorial of i by multiplying the previous factorial in the dp list (dp[-1]) with i. Take the modulus of the result with 100 to keep only the last two digits.
  6. Append the computed factorial to the dp list.
  7. After the loop, retrieve the last element from the dp list using dp[-1], which represents the factorial of n.
  8. Convert the factorial to a string using str().
  9. If the factorial has fewer than two digits, pad it with leading zeroes using the zfill() method with an argument of 2.
  10. Return the resulting string as the last two digits of the factorial.

C++




#include <iostream>
#include <vector>
#include <string>
using namespace std;
 
string last_two_digits_factorial(int n) {
    vector<int> dp(1, 1);
    for (int i = 1; i <= n; ++i) {
        dp.push_back((dp.back() * i) % 100);
    }
    return to_string(dp.back());
}
 
int main() {
    int n = 7; // Or any other value
    string result = last_two_digits_factorial(n);
    while (result.length() < 2) {
        result = "0" + result;
    }
    cout << result << endl;
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class Main {
 
    public static String lastTwoDigitsFactorial(int n) {
        List<Integer> dp = new ArrayList<>();
        dp.add(1);
 
        // Calculate factorial and store the last two digits
        for (int i = 1; i <= n; ++i) {
            dp.add((dp.get(dp.size() - 1) * i) % 100);
        }
 
        // Convert the last two digits to a string
        String result = dp.get(dp.size() - 1).toString();
 
        // Ensure the result has at least two digits by adding leading zeros if needed
        while (result.length() < 2) {
            result = "0" + result;
        }
 
        return result;
    }
 
    public static void main(String[] args) {
        int n = 7; // Or any other value
        String result = lastTwoDigitsFactorial(n);
        System.out.println(result);
    }
}


Python3




def last_two_digits_factorial(n):
    dp = [1]
    for i in range(1, n + 1):
        dp.append((dp[-1] * i) % 100)
    return str(dp[-1]).zfill(2)
n = 7  # Or any other value
result = last_two_digits_factorial(n)
print(result)
#This code is contributed by Rayudu


C#




using System;
 
class MainClass {
    static string LastTwoDigitsFactorial(int n) {
        // Initialize a list with one element (1)
        var dp = new System.Collections.Generic.List<int> { 1 };
 
        // Calculate factorial and store last two digits
        for (int i = 1; i <= n; ++i) {
            dp.Add((dp[dp.Count - 1] * i) % 100);
        }
 
        // Convert the result to a string
        return dp[dp.Count - 1].ToString();
    }
 
    public static void Main(string[] args) {
        int n = 7; // Or any other value
 
        // Get the last two digits of factorial
        string result = LastTwoDigitsFactorial(n);
 
        // Add leading zeros if needed
        while (result.Length < 2) {
            result = "0" + result;
        }
 
        // Print the result
        Console.WriteLine(result);
    }
}


Javascript




// Javascript program for the above approach
function lastTwoDigitsFactorial(n) {
    const dp = [1];
 
    // Calculate factorial and store the last two digits
    for (let i = 1; i <= n; ++i) {
        dp.push((dp[dp.length - 1] * i) % 100);
    }
 
    // Convert the last two digits to a string
    let result = dp[dp.length - 1].toString();
 
    // Ensure the result has at least two digits by adding leading zeros if needed
    while (result.length < 2) {
        result = "0" + result;
    }
 
    return result;
}
 
// Test the function with a sample value
const n = 7; // Or any other value
const result = lastTwoDigitsFactorial(n);
console.log(result);
 
// This code is contributed by Susobhan Akhuli


Output

40


Time Complexity:

The initialization of the dp list with a single element takes constant time, O(1).
The loop iterates n times, performing constant time operations in each iteration. Therefore, the loop has a time complexity of O(n).
Within the loop, the list dp is appended with a new element, which takes constant time, O(1).
The computation of (dp[-1] * i) % 100 also takes constant time, O(1).
Finally, retrieving the last element from the dp list and converting it to a string using str() takes constant time, O(1).
Hence, the overall time complexity of the last_two_digits_factorial() function is O(1) + O(n) + O(1) + O(1) + O(1) = O(n).

Auxiliary Space:

The dp list is initialized with a single element, taking constant space, O(1).
The dp list grows to store n+1 elements, so it occupies space proportional to n. Hence, the space complexity for the dp list is O(n).
The additional space used to store the result variable and the function parameters is constant, O(1).
Therefore, the overall space complexity of the last_two_digits_factorial() function is O(n) + O(1) = O(n).



Last Updated : 16 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads