Here is my code:
def func(n):
sum_digits_n = 0
for i in str(n):
sum_digits_n+=int(i)
num = n+1
while True:
s = 0
for i in str(num):
s+=int(i)
if s==sum_digits_n:
return num
break
else:
num += 1
It works for small to moderate sized n
. But it takes forever to run with big values of n
. How can I optimize it?
For example, let's check the run times for different sized inputs:
import time
inputs = [7,70,700,7000,70000,700000,7000000,70000000]
for i in inputs:
t = time.time()
ans = func(i)
print('Input: {}. Ans: {}. Time taken: {}s\n'.format(i, ans, time.time()-t))
As you can see, even with a not-so-huge input as 70 million, the code takes ~1.5 mins to run.