Project Euler : Numbers That Are Fifth Powers Of Their Digits

The idea in solving this problem was pretty simple. If you consider the digits a, b, c, d, e and f, the sum of their 5th powers will always be the same irrespective of their ordering. So, instead of iterating over all the numbers, I chose to iterate over all the collection of the digits. For each collection, find the sum of the fifth powers of the digits, get the digits of the sum ordered in ascending order and if the digits of the sum and the collection are the same, then the sum is a number that we wanted.

For example, consider the digits 0, 0, 0, 1, 4, 5. Now the sum of their fifth powers is 4150. I retrieve the digits of the sum in ascending order – 0, 0, 0, 1, 4, 5. See, the two are the same. Thus 4150 is the number we were looking for.

It takes just some 5000 iterations to complete the search.

The main class:

package problems_21_30;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Problem_30 {
	private int[] m_fifthPowers;

	public Problem_30() {
		m_fifthPowers = new int[] { 0, 1, 32, 243, 1024, 3125, 7776, 16807, 32768, 59049 };
	}

	private int[] getDigits(int number) {
		int[] digits = new int[6];
		int i = 0;

		while (number > 0) {
			digits[i++] = number % 10;
			number /= 10;
		}
		Arrays.sort(digits);

		return digits;
	}

	public List<Integer> getSillyNumbers() {
		List<Integer> sillyNumbers = new ArrayList<Integer>();

		for (int a = 0; a < 10; a++)
			for (int b = a; b < 10; b++)
				for (int c = b; c < 10; c++)
					for (int d = c; d < 10; d++)
						for (int e = d; e < 10; e++)
							for (int f = e; f < 10; f++) {
								int sum = m_fifthPowers[a] + m_fifthPowers[b] + m_fifthPowers[c] + m_fifthPowers[d]
								        + m_fifthPowers[e] + m_fifthPowers[f];
								int[] digits = getDigits(sum);
								if (a == digits[0] &amp;amp;&amp;amp; b == digits[1] &amp;amp;&amp;amp; c == digits[2] &amp;amp;&amp;amp; d == digits[3]
								        &amp;amp;&amp;amp; e == digits[4] &amp;amp;&amp;amp; f == digits[5])
									sillyNumbers.add(sum);
							}

		return sillyNumbers;
	}

	public static void main(String[] args) {
		List<Integer> sillyNumbers = new Problem_30().getSillyNumbers();

		int sum = -1;
		for (int number : sillyNumbers)
			sum += number;

		System.out.println(sum);
	}

}

Popularity: 13% [?]

Related posts:

  1. Project Euler : Digits Of Sum of 1^1 + 2^2 + 3 ^ 3 …
  2. Project Euler : Evaluate Sum Of All Amicable Pairs
  3. Project Euler : Verifying Triangle Words
  4. Project Euler : Greatest Product of 4 Numbers In A 20×20 Grid
  5. Project Euler : Sum Of Digits In a^b