1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import threading import time
def main(): n = 7 power_dict = {str(i): i ** n for i in range(10)} lock = threading.Lock() results = []
def check_narcissistic(start, end): for i in range(start, end): num_str = str(i) total = sum(power_dict[digit] for digit in num_str) if total == i: with lock: results.append(i)
num_threads = 8 total_numbers = 10 ** n - 10 ** (n - 1) numbers_per_thread = total_numbers // num_threads
threads = []
for i in range(num_threads): start = 10 ** (n - 1) + i * numbers_per_thread end = start + numbers_per_thread thread = threading.Thread(target=check_narcissistic, args=(start, end)) threads.append(thread) thread.start()
for thread in threads: thread.join()
results.sort()
if __name__ == '__main__': for i in range(10): start_time = time.time() main() end_time = time.time() execution_time = end_time - start_time print("执行时间:{:.2f} 秒".format(execution_time))
|