[Euler]Problem 30 - Digit fifth powers

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44

As 1 = 14 is not a sum it is not included.

The sum of these numbers is 1634 + 8208 + 9474 = 19316.

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.


import java.util.HashMap;
import java.util.Map;

public class DigitFifthPowers {
	Map<Integer, Double> map = new HashMap<Integer, Double>();

	public static void main(String[] args) {
		long before = System.currentTimeMillis();

		new DigitFifthPowers().calculate();

		System.out.println("elapsed time is : " + (System.currentTimeMillis() - before));
	}

	private void calculate() {
		int count = 0;

		for (int i = 0; i < 10; i++) {
			map.put(i, Math.pow(i, 5));
		}

		System.out.print("the numbers that can be written as the sum of fifth powers of their digits is : ");

		for (int i = 2; i < 1000000; i++) {
			if (isThisIt(i)) {
				System.out.print(i + " ");
				count += i;
			}
		}

		System.out.println();
		System.out.println(count);
	}

	private boolean isThisIt(int i) {
		Double sumOfDigits = 0d;
		int temp = i;

		while (temp > 0) {
			sumOfDigits += map.get(temp % 10);
			temp /= 10;
		}

		return sumOfDigits == i;
	}

}


console:

the numbers that can be written as the sum of fifth powers of their digits is : 4150 4151 54748 92727 93084 194979 
443839
elapsed time is : 111

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