Skip to content

Instantly share code, notes, and snippets.

@MikaelCarpenter
Last active November 17, 2016 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikaelCarpenter/0ba9b77c2355e232e9135063a6ccf2fd to your computer and use it in GitHub Desktop.
Save MikaelCarpenter/0ba9b77c2355e232e9135063a6ccf2fd to your computer and use it in GitHub Desktop.
from time import time
test_range = range(100, 146511209)
power_ref = {n: {i: i**n for i in range(1,10)} for n in range(2,10)}
def is_narcissistic(x):
string = str(x)
digits = sorted([int(i) for i in string if i != '0'], reverse=True)
digit_counts = {i: digits.count(i) for i in set(digits)}
n = len(string)
sum = 0
for digit, count in digit_counts.items():
sum += count*power_ref[n][digit]
if sum > x:
return False
return sum == x
start = time()
for i in test_range:
if is_narcissistic(i):
print("[{:8.3f}] {}".format(time() - start, i))
@tiphaine
Copy link

Elegant way to generate the precomputed powers!

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