Euler Problem 34

145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.

Find the sum of all numbers which are equal to the sum of the factorial of their digits.

Note: as 1! = 1 and 2! = 2 are not sums they are not included.

This one is a staight forward as it seems. Don’t need to iterate too high as the sum of lots of 9-bang’s can’t catch up to a long digit number consisting of many nines.

public class Euler34
{
    public static void main(String[] args)
    {
        System.out.format(“Problem 34:\n”);
        Euler34 e = new Euler34();
        System.out.format(“Answer = %s\n”, e.Problem());
    }
    public String Problem ()
    {
        long bigSum = 0;
        for (int i = 3; i <= 100000; i++)
        {
            int littleSum = 0;
            String digits = String.valueOf(i);
            for (int n = 0; n <= digits.length()-1; n++)
                littleSum += F(digits.charAt(n)-48);
            if (littleSum == i)
            {
                bigSum += littleSum;
                System.out.format(“%s:%d\n”, i, littleSum);
            }
        }
        return String.valueOf(bigSum);
    }
    public int F (int d)
    {
        int sum = 1;
        for (int i = d; i >= 1; i–)
            sum *= i;
        return sum;
    }
}

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 )

Connecting to %s