In: Computer Science
**Please write in Java, in a very simple/beginner coding
style/language - thank you!**
Directions: Given a factorial n!. Find the sum of its
digits, and the number of trailing zeros (ie: the number of zeros
at the end of the factorial).
Input: integer nn, a non-negative integer where
n≤20n≤20
Output: integer xyxy, the concatenation of x and
y, where x is the sum of the digits in n! and y is the number
of the zeros in n!) Note, 0≤x,y0≤x,y.
Example: Consider the factorial: 5! = 5x4x3x2x1 = 120. The sum of its digits is 1+2+0 = 3, and the number of zeros at the end of 5! = 120 is 1. Then here, x = 3 and y = 1, so the answer/output for 5! is 31.
Extra Credit: allow the user to choose any integer n≥1
import java.util.Scanner;
class Factorial {
// function to find total zeros
static int find_zeros(long factorial) {
int zeros = 0;
// till factorial is divisible by 10
while (factorial % 10 == 0) {
zeros += 1;
factorial /= 10;
}
return zeros;
}
// function to find sum of digits
static int find_sum(long factorial) {
int sum = 0;
while (factorial > 0) {
sum += factorial % 10;
factorial /= 10;
}
return sum;
}
public static void main(String[] args) {
// read n
Scanner sc = new Scanner(System.in);
System.out.print("Enter n: ");
int n = sc.nextInt();
// compute factorial
long factorial = 1;
for (int i = 1; i <= n; i++)
factorial *= i;
int sum = find_sum(factorial);
int zeros = find_zeros(factorial);
System.out.printf("%d%d", sum, zeros);
}
}
.
Output:
.