Nipuna Upeksha
Nipuna Upeksha

Reputation: 416

Java Algorithm for Project Euler Q20

n! means n X (n - 1) X ... X 3 X 2 X 1

For example, 10! = 10 X 9 X ... X 3 X 2 X 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!

import java.util.*;
class ProjectEuler_20{
    public static double factorial(double number){
        double num=1;
        for(int i=2;i<=number;i++){
            num=num*i;
            }
        return num;
        }
    public static void main(String args[]){
        double number=factorial(100);
        long num=(long)number;
        long sum=0;
        for(int i=0;num>0;i++){
            sum=sum+num%10;
            num=num/10;
            }
        System.out.println(sum);
        }
    }

Why do I always get the sum of the digits of Long.MAX_VALUE? Is there a way to approach for the real answer?

Upvotes: 2

Views: 162

Answers (1)

Bohemian
Bohemian

Reputation: 425083

double cannot accurately hold a number as large as 100!; it can only hold an approximation.

You must use BigInteger to accurately perform the calculation.

Here's a 1 line answer:

int sum = IntStream.range(1, 101)       // stream ints from 1 up to 100
        .mapToObj(String::valueOf)      // ready for BigInteger constructor
        .map(BigInteger::new)           // create a BigInteger from the String
        .reduce(BigInteger::multiply)   // multiply them all together
        .get().toString().chars()       // stream the digits of the result
        .map(i -> i - '0')              // convert char as int to its digit value
        .sum();                         // sum the digits

Result:

648

fyi, 100! is 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Upvotes: 1

Related Questions