Compute 50! with BigInteger, print its number of digits, the sum of its digits and its trailing zeros, and compare with what long overflows to for 21!.
Solution
Main.java
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger f = BigInteger.ONE;
for (int i = 2; i <= 50; i++) f = f.multiply(BigInteger.valueOf(i));
String s = f.toString();
int digitSum = 0;
for (char c : s.toCharArray()) digitSum += Character.getNumericValue(c);
int zeros = s.length() - s.replaceAll("0+$", "").length();
System.out.println("50! has " + s.length() + " digits, digit sum " + digitSum + ", " + zeros + " trailing zeros");
long lf = 1;
for (int i = 2; i <= 21; i++) lf *= i;
BigInteger exact = BigInteger.ONE;
for (int i = 2; i <= 21; i++) exact = exact.multiply(BigInteger.valueOf(i));
System.out.println("21! long = " + lf + ", exact = " + exact + ", fits in long: " + (exact.bitLength() < 64));
}
}
Output Verified by compiling and running
50! has 65 digits, digit sum 216, 12 trailing zeros
21! long = -4249290049419214848, exact = 51090942171709440000, fits in long: false
long silently overflows past 20!; BigInteger grows as needed. 50! has ⌊50/5⌋ + ⌊50/25⌋ = 12 trailing zeros.
More Object Class and Wrapper Classes practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!