I tried to solve this about factorials but it's not giving the right answer

Viewed 50

this is the question: Write a python code to find all the integers less than 50,000 that equal to the sum of factorials of their digits. As an example: the number 7666 6= 7! + 6! + 6! + 6! but 145=1!+4!+5!

note: im not allowed to use any specific factorial function.

my solution:

import math
from numpy import *
for i in range(5):
    for j in range(10):
        for k in range(10):
            for l in range(10):
                for m in range(10):
                    x=1*m+10*l+100*k+1000*j+10000*i
                    def fact(m):
                        fact=1
                        for i in range(1,m+1):
                            fact=fact*i
                        return fact
                    y=fact(i)+fact(j)+fact(k)+fact(l)+fact(m)
                    if x==y :
                        print(x)
1 Answers

Hint 1

The reason this does not give you a correct answer is because there will be times where your code considers 0 to be a digit.

For example fact(0)+fact(0)+fact(1)+fact(4)+fact(5) gives 147

because fact(0) is 1.

Hint 2

While your manner of iterating is interesting and somewhat correct, it is the source of your bug.

Try iterating normally from 1 to 50000 then figure out the sum of the digits a different way.

for i in range(50000):
    # ...

Solution

Since this is StackOverflow, I offer a solution straightaway.

Use a function like this to find the sum of digits of a number:

def fact(m):
    fact=1
    for i in range(1,m+1):
        fact=fact*i
    return fact

def sumOfFactOfDigits(x):

    # This function only works on integers
    assert type(x) == int

    total = 0

    # Repeat until x is 0
    while x:

        # Add last digit to total
        total += fact(x%10)

        # Remove last digit (always ends at 0, ie 123 -> 12 -> 1 -> 0)
        x //= 10

    return total


for i in range(50000):
    if i == sumOfFactOfDigits(i):
        print(i)

Note

You should move your definition of fact outside of the loop.

Related