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

Problem 34(Digit factorials) 본문

Project Euler

Problem 34(Digit factorials)

(이경수) 2019. 6. 2. 09:45

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.

 

In Python:

import time
import math

startTime = time.time()
result = 0
for n in range(3, 10 ** 7):
    nList = list(str(n))
    sumFact = 0
    for num in nList:
        sumFact += math.factorial(int(num))
        if n == sumFact:
            result += n
print(result)
print(time.time() - startTime, "seconds")

Run time: 43.40570092201233 seconds

 

In Java:

package project_euler31_40;

public class Euler34 {
	public static int factorial(int n) {
		if (n == 0 || n == 1) {
			return 1;
		} else {
			return n * factorial(n - 1);
		}
	}
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		int result = 0; 
		int sumFact = 0;
		int div = 0;
		int r = 0;
		int factorialList[] = new int[10];
		for (int i = 0; i < 10; i++) {
			factorialList[i] = factorial(i);
		}
		for (int n = 3; n < Math.pow(10, 7); n++) {
			sumFact = 0;
			div = n;
			while(true) {
				if (div > 0) {
					r =  Math.floorMod(div, 10);
					div = Math.floorDiv(div, 10);
					sumFact += factorialList[r];
				} else {
					break;
				}
			}
			if (n == sumFact) {
				result += n;
			}
		}
		System.out.println(result);
		long endTime = System.currentTimeMillis();
		System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");
	}
}

Run time: 0.467seconds

 

Solution: 40730

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

Problem 36(Double-base palindromes)  (0) 2019.06.06
Problem 35(Circular primes)  (0) 2019.06.04
Problem 33(Digit cancelling fractions)  (0) 2019.05.27
Problem 32(Pandigital products)  (0) 2019.05.19
Problem 31(Coin sums)  (0) 2019.05.12
Comments