Find The Last Two Digits of the Factorial of a Given Number in Java
Given an Integer N, our task is to find the last two digits of the N factorial. The factorial of a number can be defined as the product of all positive integers that are less than or equal to a certain positive integer. In this case we focus on finding the product of last two digits instead of unit digits.
Example 1:
Input:
int num = 5
Output:
The Last Two digits of a factorial of a number is 20
Explanation:
If we calculate the factorial of the num = 5, then we get (5! = 5 * 4 * 3 * 2 * 1 = 120), and the factorial of the number is 120. In the result, the last two digits are 20. Hence it returns the output as 20.
Example 2:
Input:
int num = 3
Output:
It cannot be determined
Explanation:
If we calculate the factorial of the num = 3, then we get (3! = 3 * 2 * 1 = 6), and the factorial of the number is 6. Here, the total number of digits in factorial is "One." Hence it cannot be determined.
Example 3:
Input:
int num = 5
Output:
The Last Two digits of a factorial of a number is 00
Explanation:
If we calculate the factorial of the num = 11 then we get, (11! = 11 * 10 * 9 * 8 *7 * 6 * 5 * 4 * 3 * 2 * 1 = 39916800) the factorial of number is 39916800. In the result, the last two digits are 00. Hence it returns the output as 00.
Approach: Native Approach
For N >= 10, the last two places of its factorial will only contain 0's. As a result, N!% 100 for any N greater than 10 is always 0. So, if N = 10, we simply compute the factorial and remove the last two digits.
Implementation:
FileName: LastTwoDigits.java
import java.io.*; import java.util.*; public class LastTwoDigits { static void Factorial(int num) { if (num >= 10) { System. out.print("The Last Two digits of a factorial of a number is 00"); return; } else if(num <= 3) { System. out.print("Cannot be determined"); return; } else { int fact = 1; for (int i = 1; i <= num; i++) { fact = (fact * i) % 100; } System.out.print("The Last Two digits of a factorial of a number is " + fact ); } } public static void main(String args[]) { int num = 8; Factorial(num); } }
Output:
The Last Two digits of a factorial of a number is 20
Complexity Analysis:
The time complexity for the above program is O(n) since a single for loop is used, and the space complexity of the program remains constant, which is O(1).