Project Euler NO34

145 是一個奇怪的數字, 因爲 1! + 4! + 5! = 1 + 24 + 120 = 145.
找出所有等於各位數字階乘之和的數字之和。

注意: 因爲 1! = 1 和 2! = 2 不是和的形式,所以它們不算在內。



import java.util.Arrays;

public class Problem34
{
	public static void main(String[] args)
	{
		long start = System.currentTimeMillis();
		System.out.print("answer:  ");
		
		howmany();
		
		long end = System.currentTimeMillis();
		System.out.print("time:  ");
		System.out.println(end - start);
	}
	
	static void howmany()
	{
		int total = 0;
		int array[] = new int[10];//用數組存下 0 ~ 9 的階乘加快計算
		for (int i = 0; i <= 9; i++)
		{
			array[i] = jiecheng(i);
		}
		for (int i = 11; i <= 2540160; i++)// 9! * 7 爲最大
		{
			int t = i;
			int sum = 0;
			while (t != 0)
			{
				sum += array[t % 10];
				t /= 10;
			}
			if (sum == i)
			{
				total += i;
			}
		}
		System.out.println(total);
	}
	
	static int jiecheng(int n)
	{
		int sum = 1;
		for (int i = 2; i <= n; i++)
		{
			sum *= i;
		}
		
		return sum;
	}
}



answer:  40730
time:  90

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章