Project Euler – Problem # 20 – Solved with Java

Find the sum of digits in 100!

n! means n * (n – 1) * … * 3 * 2 * 1

For example, 10! = 10 * 9 * … * 3 * 2 * 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

['9332621544394415268169923885626670049071596826438162146859296389521759999
32299156089414639761565182862536979208272237582511852109168640000000000000
00000000000']

So 100! gives you a long number, what the question is asking is to sum each digit in that long number.

import java.math.BigInteger;

public class Problem_20 {
	public static void main(String args[]){
		BigInteger n = BigInteger.valueOf(100);
		int Sum = 0;
		BigInteger result = (factorial(n));
		String string_result = String.valueOf(result);
		
		for(int i = 0; i <= string_result.length() - 1; i ++){
			Character c = new Character(string_result.charAt(i));
		    String s = c.toString();
		    int n1 = Integer.parseInt(s);
			Sum += n1;
		}
		System.out.format("Sum = %d%n", Sum);
	}
	public static BigInteger factorial( BigInteger n )
	{
			if ( n.compareTo(BigInteger.ZERO) <= 0 ) { // base case
				return BigInteger.ONE;
			}
			else  {  // general case
				return ( n.multiply(factorial ( n.subtract(BigInteger.ONE)) ) );
			}
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s