LearnFrenzy
Sign in Take a free test

Object Class and Wrapper Classes · Object and Wrapper Programs · Question 9

Big factorials and digit sums with BigInteger in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links