def fac_sum(num, fac_map): tale = 0 while num: tale += fac_map[num % 10] num //= 10 return tale def fac_update(fac_map, num, target, fac_list, frm_set = set()): s_num = str(sorted(str(num))) if s_num in frm_set: fac_list.append(num) return loop = [] shift = num while shift not in loop: loop.append(shift) shift = fac_sum(shift, fac_map) if len(loop) == target: fac_list.append(num) frm_set.add(s_num) def count(limit, target): fac_map = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] tale = [] for x in range(limit): fac_update(fac_map, x, target, tale) return tale print(len(count(1000000, 60)))