Skip to main content

narcissus 水仙花數

· One min read
def num_to_dict(num):
num = [int(_) for _ in str(num)]
dic = {}
for e in num:
dic[e] = dic.get(e, 0) + 1
return dic


def my_narcissus(N, M):
re, power = [], {}
for num in range(N, M):
if not num%N or not num%(10**6):
print('.', end='')
dic = num_to_dict(num)
lng = len(str(num))
cnt = 0
for key in dic:
if not (key, lng) in power:
power[(key, lng)] = key**lng
cnt += dic[key] * power[(key, lng)]
if cnt == num:
re.append(num)
print()
return re


import time
scale = 10**6
for l in range(5):
start_time = time.time()
print(l+1, '位數', end='')
t = narcissus(10**l, 10**(l+1))
time_spend = time.time()-start_time
print(t)
print('時間:', time_spend)
print('時間比例:', time_spend/(9*10**l)*scale, '\n')