Skip to content

Instantly share code, notes, and snippets.

@tiphaine
Last active November 17, 2016 22:02
Show Gist options
  • Save tiphaine/2070004d8054436aff3563c65a9c532d to your computer and use it in GitHub Desktop.
Save tiphaine/2070004d8054436aff3563c65a9c532d to your computer and use it in GitHub Desktop.
Detect narcissistic numbers.
from collections import defaultdict
from time import time
def is_narcissistic(x):
sum = 0
digits = sorted([int(digit) for digit in str(x)], reverse=True)
power = len(digits)
for digit in digits:
sum += powers[power][digit]
if sum > x:
return False
return sum == x
def precompute_powers(n):
powers = defaultdict(dict)
for i in range(2, n+1):
for digit in range(10):
powers[i][digit] = digit ** i
return dict(powers)
upper_bound = 100000000000
powers = precompute_powers(len(str(upper_bound)))
start = time()
for number in range(11, upper_bound):
if is_narcissistic_memory(number):
print("[{:8.3f}] {}".format(time()-start, number))
@MikaelCarpenter
Copy link

that reverse sort is nice! works well with the escape door of if sum > x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment