Is there a better/efficient way of doing this?
Link: HackerRank | Project Euler #254.
The time and space complexity increases exponentially. Any clues about how to improve the code or a change of approach would be very helpful.
# Enter your code here. Read input from STDIN. Print output to STDOUT
def factorial(num):
result = 1
for i in range(1, num+1):
result *= i
return result
def f(n):
fact_table = [factorial(i) for i in range(10)]
return sum([fact_table[int(i)] for i in str(n)])
def sf(n):
return sum([int(i) for i in str(f(n))])
def g(i):
n = 1
sf_val = sf(n)
while sf_val != i:
n += 1
sf_val = sf(n)
return n
# print(g(48))
def sg(i):
return sum([int(i) for i in str(g(i))])
# print(sg(3))
def solve(n, m):
result = sum([sg(i) for i in range(1,n+1)])
return result % m
# print(solve(3, 1000))
if __name__ == '__main__':
result = []
for i in range(int(input())):
n, m = map(int, input().split())
result.append(solve(n, m))
for i in result:
print(i)