project euler 34

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;
			}
		}
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值