# Searches for perfect numbers among the integers 1 - ... # This version finds exactly 5 perfect numbers. import itertools import math # for sqrt import os import time # returns the sum of the proper divisors of n def sum_divisors(n): root = int(math.sqrt(n)) result = sum((k + n // k for k in \ range(2, root + 1) if n % k == 0)) + 1 if n == root * root: result -= root return result # Runs the given function f, measuring how long it took to run. # Returns the elapsed runtime at the end of the call. def measure_runtime(f): start_time = time.time() f() elapsed_time = time.time() - start_time return elapsed_time # Finds and prints the first 5 perfect numbers. def find_perfect_numbers(): print("Searching for perfect numbers:") perfects = (n for n in itertools.count(1) if n == sum_divisors(n)) for k in itertools.islice(perfects, 5): print(k) def main(): runtime = measure_runtime(find_perfect_numbers) print("time =", runtime, "sec") main()