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 *
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 **
Step by Step Solution
3.41 Rating (154 Votes )
There are 3 Steps involved in it
Step: 1
Answer import javautil class Main static int dig 1 1 2 6 4 2 2 4 2 8 static int lastNon0Digitint n i...See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started