Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Factorials and BigInteger Code - Bug - JAVA

I am not receiving the correct solution. If you find what is wrong, can you explain how you broke it down and found the bug. Thanks so much.

package euler20;

import java.math.BigInteger;

public class sumDigitsIn100Factorial {

        public static final int n = 100;

        public static void main(String[] args) {

            long startTime = System.currentTimeMillis();

            System.out.println("100! = " + factorial(n));
            System.out.println("Sum of all digits in 100! = " + sumOfDigits(factorial(n)));

            long endTime = System.currentTimeMillis();
            System.out.println("Time: " + (endTime - startTime) + " ms");

        }

        public static BigInteger factorial(int n1) {

            BigInteger n = BigInteger.ONE;

            for (int i = 1; i <= n1; i++) {
                n = n.multiply(BigInteger.valueOf(i));
            }
            return n;
        }

        public static int sumOfDigits(BigInteger n1) {

            String bigIntStr = factorial(n).toString();
            int sum = 0;

            for (int i = 1; i <= bigIntStr.length(); i++) {
                sum += Integer.parseInt(String.valueOf(i));
            }
            return sum;
        }
}

1 Answer

Hi Diego - It looks like that the issue is in the sumOfDigits function. You've converted the return value of factorial(n) to a String, but instead of adding the digits, the individual characters in that String, you're adding up the numbers from 1 thru the length of the String. For example, 6! is 720. The sum of digits should be 7+2+0=9. But you're adding 1+2+3 and you end up with 6. This is what I did:

public static int sumOfDigits(BigInteger n1) {
    String bigIntStr = factorial(n).toString();
    System.out.println(bigIntStr);
    int sum = 0;

    for (char digit : bigIntStr.toCharArray()) {
        sum += Integer.parseInt(digit + "");    
    }    
    return sum;
}

Thanks. What is the purpose of the " " marks after digit??

Glad I could help! The parseInt() method expects a String so I had to convert digit, which is a char, to a String by concatenating an empty String to it.