Project Euler: Problem 34 – Digit factorials

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.

Idea:

Not knowing how high to calculate, I again just took a shot in the dark with a really high number. Since we’re only calculating the factorial from 0 – 9, I calculated them once and put them into an array for easy access.
 
Then just looped from 3 to at least 400,000 (since 9! = 362,880) and add up the factorial of the digits and see if it equals the original number (in this case, I looped to 1 million). If the sum of the digit factorials is equal to the original number, add that number to the existing sum.

int answer = 0;

int[] factorials = new int[10];
factorials[0] = 1;
for(int i = 1; i < factorials.length; i++) {
   factorials[i] = factorials[i-1]*i;
}

for(int i = 3; i < 1000000; i++) {
   int tmp = i;
   int sum = 0;
   while(tmp > 0) {
      sum += factorials[tmp%10];
      tmp = tmp/10;
   }
   if(sum == i) {
      answer += sum;
   }
}