Problem 34
Digit factorials
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.
各位数字的阶乘
145是个有趣的数,因为1! + 4! + 5! = 1 + 24 + 120 = 145。
找出所有各位数字的阶乘和等于其本身的数,并求它们的和。
注意:因为1! = 1和2! = 2不是和的形式,所以它们并不在讨论范围内。
package projecteuler;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class Prj34 {
/**
* 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.
*/
@Test
public void test(){
System.out.println(Calculator.calculate());
}
public static class Calculator{
public static long calculate(){
long val = (long) Math.pow(10, getBits() - 1);
Set<Long> set = new HashSet<Long>();
for( long i = 3 ; i < val ; i ++){
if( checkNum(i)){
set.add(i);
System.out.println(i);
}
if( i % 10000 == 0){
System.out.println("iter =" + i);
}
}
long sum = 0;
for( long val_ : set){
sum += val_ ;
System.out.println(val_);
}
System.out.println(sum);
return sum;
}
private static int getBits(){
int val = NN.NINE.getVal();
int bits = 1;
while( val * bits >= Math.pow(10, bits - 1)){
bits += 1;
}
return bits;
}
private static boolean checkNum(long i) {
int sum = 0;
int num = 0;
long val = i;
while( val >= 10){
num = Long.valueOf( val % 10).intValue();
sum += NN.getNN(num ).getVal();
val /= 10;
}
num = Long.valueOf( val).intValue();
sum += NN.getNN(num).getVal();
if( sum == i){
return true;
}else {
return false;
}
}
}
public static enum NN{
ZERO(0),
ONE(1),
TWO(2 * 1),
THREE(3 * 2 * 1),
FOUR(4 * 3 * 2 * 1),
FIVE(5 * 4 * 3 * 2 * 1),
SIX(6 * 5 * 4 * 3 * 2 * 1),
SEVEN(7 * 6 * 5 * 4 * 3 * 2 * 1),
EIGHT(8 * 7 * 6 * 5 * 4 * 3 * 2 * 1),
NINE(9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1);
private int val;
private NN(int val){
if( val == 0){
this.val = 1;
return;
}
this.val = val;
}
public int getVal(){
return this.val;
}
public static NN getNN(int val){
switch (val) {
case 0: return ZERO;
case 1: return ONE;
case 2: return TWO;
case 3: return THREE;
case 4: return FOUR;
case 5: return FIVE;
case 6: return SIX;
case 7: return SEVEN;
case 8: return EIGHT;
case 9: return NINE;
default:
return ZERO;
}
}
}
}