이경수 선생님의 수학실험실

Problem 30(Digit fifth powers) 본문

Project Euler

Problem 30(Digit fifth powers)

(이경수) 2019. 5. 12. 17:02

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 = 1^{4} + 6^{4} + 3^{4} + 4^{4} \)
\(8208 = 8^{4} + 2^{4} + 0^{4} + 8^{4} \)
\(9474 = 9^{4} + 4^{4} + 7^{4} + 4^{4} \)

As \(1 = 1^{4}\) 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.

 

In Python:

#PE30 Digit fifth powers
import time

startTime = time.time()
sumResult = 0
for num in range(10, pow(10, 6)):
    sumList = 0
    num = list(str(num))
    for i in num:
        sumList += int(i) ** 5
    if int(''.join(num)) == sumList:
        sumResult += int(''.join(num))
print(sumResult)
print(time.time() - startTime, "seconds")

Run time: 4.87015700340271 seconds

 

In Python:

#PE30 Digit fifth powers
import time

startTime = time.time()
resultList = []
for num in range(10, pow(10, 6)):
    sumDigit = sum([int(i) ** 5 for i in str(num)])
    if int(num) == sumDigit:
        resultList.append(int(num))
print(sum(resultList))
print(time.time() - startTime, "seconds")

Run time: 4.195937633514404 seconds

 

In Java:

package project_euler21_30;

import java.util.ArrayList;

public class Euler30 {
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		int sumDigit = 0;
		int sumResult = 0;
		String nStr;
		String data[];
		ArrayList<Integer> resultList = new ArrayList<Integer>();
		for (int i = 10; i < Math.pow(10, 6); i++) {
			nStr = String.valueOf(i);
			data = nStr.split("");
			sumDigit = 0;
			for (String s : data) {
				sumDigit += Math.pow(Integer.parseInt(s), 5);
			}
			if (i == sumDigit) {
				resultList.add(sumDigit);
			}
		}
		for (Integer i : resultList) {
			sumResult += i;
		}
		System.out.println(sumResult);
		long endTime = System.currentTimeMillis();
		System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");
	}
}

Run time: 1.348seconds

 

Solution: 443839

'Project Euler' 카테고리의 다른 글

Problem 32(Pandigital products)  (0) 2019.05.19
Problem 31(Coin sums)  (0) 2019.05.12
Problem 29(Distinct powers)  (0) 2019.05.12
Problem 28(Number spiral diagonals)  (0) 2019.05.12
Problem 27(Quadratic primes)  (0) 2019.05.12
Comments