Last active
November 17, 2016 22:02
-
-
Save tiphaine/2070004d8054436aff3563c65a9c532d to your computer and use it in GitHub Desktop.
Detect narcissistic numbers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
that reverse sort is nice! works well with the escape door of
if sum > x