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.
临界点为 9! * 7 = 2540160
public class DigitFactorials {
public static void main(String[] args) {
long before = System.currentTimeMillis();
new DigitFactorials().calculate();
System.out.println("elapsed time is : " + (System.currentTimeMillis() - before));
}
private void calculate() {
int number = 3;
int sum = 0;
int temp = 0;
while (number <= 2540160) {
int sumOfDigits = 0;
temp = number;
while (temp > 0) {
sumOfDigits += calculateFactorial(temp % 10);
temp = temp / 10;
}
if (sumOfDigits == number) {
sum += sumOfDigits;
}
number++;
}
System.out.println("sum of all numbers is : " + sum);
}
private int calculateFactorial(int a) {
if (a == 0) {
return 1;
}
return a * calculateFactorial(a - 1);
}
}
console :
sum of all numbers is : 40730
elapsed time is : 211