DEV Community

Discussion on: Write a script to find "Perfect Numbers"

Collapse
 
florimondmanca profile image
Florimond Manca • Edited

A (lazy but slow) Python solution which hasn't even yielded 33550336 in 5 minutes, despite a subtle optimization allowing to find divisors in O(√n)… Probably could use some optimization to prevent trying all possible integers. :-)

def find_divisors(n: int):
    divisors = []
    m = 1
    while m * m < n:
        if n % m == 0:
            yield m
            if m != 1:
                yield n / m
        m += 1


def is_perfect(n: int) -> bool:
    return sum(find_divisors(n)) == n


if __name__ == '__main__':
    from itertools import cycle
    all_integers = cycle()
    for n in filter(is_perfect, all_integers):
        print(n)