Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Euler 34 Help [Python]

Tags:

python

The problem is:

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.

# Project Euler Problem 34
def factorial(num):
    """Factorial"""
    product = num
    for i in range(2, num):
        product *= i
    return product

def check_sum(number):
    list_digits = list(str(number))
    check_sum = 0
    for digit in list_digits:
        check_sum += factorial(int(digit))
    if check_sum == number:
        return True

def find_final_sum():
    """Find the sum of all the numbers."""
    final_list = []
    final_sum = 0
    counter = 3
    while counter < 200000:
        if check_sum(counter):
            final_list.append(counter)
            counter += 1
        else:
            counter += 1

    for j in final_list:
        final_sum += j
    print(final_sum)

find_final_sum()

I defined a function to find factorials. Then I defined a function to check if a number is equal to the sum of the factorials of its digits. Finally, I check numbers from 3 to 200000. If a number works, I put it in a list. At the end, I sum up the list and print it.

This code only gives me 145 as the answer. I can't see what I'm doing wrong, could anyone help?

I'm not trying to post a solution to the Euler problem.

like image 353
RandomCoder Avatar asked Feb 11 '26 01:02

RandomCoder


1 Answers

Your factorial function is incorrect as it falsely calculates 0! as 0. You can fix it like this:

def factorial(num):
    """Factorial"""
    if num < 2:
        return 1
    ...

then your code will print 40730.

PS: The only other curious number in your range is 40585.

like image 65
Selcuk Avatar answered Feb 13 '26 15:02

Selcuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!