Find last non-zero digit in n! Description For a given integer n, find the last non-zero digit
Question:
Find last non-zero digit in n!
Description
For a given integer n, find the last non-zero digit in thefactorial of n.
n! = n * (n-1) * (n-2) * .... * 3 * 2 * 1
Input format:
The first line should be the value of n.
Output format:
In the first line, print the last non-zero digit of n!.
Sample Input:
5
Sample Output:
2
Sample Input:
10
Sample Output:
8
code:
import java.util.*;
public class Source {
public static void main(String[] args) {
Scanner s = newScanner(System.in);
int n = s.nextInt();
System.out.print(lastNonZeroDigit(n));
}
// Method to find the last digit of n!
static int lastNonZeroDigit(int n) {
// Write your code here
}
}
I have tried many times but did not approach insolutions:
my solution
static int lastNonZeroDigit(int n) { // Write your code here if (n<=10) return n;
if (((n / 10) % 10) % 2 == 0) return (6 * lastNonZeroDigit(n / 5) * (n % 10) %10);else return (4 * lastNonZeroDigit(n / 5) * (n % 10) % 10);input: 5
output: 5
** correct me where I am wrong **