用Python代码实现1000以内的完数

题目

编程实现打印完数。一个数如果恰好等于它的因子之和,这个数就称为“完数”。
例如6 的因子为 1、 2、 3,而6=1+2+3,因此6是“完数”。
编程序找出 1000 之内的所有完数。

编写

def is_perfect_number(number):
    divisors = [1]  # 1是任何数的因子
    for i in range(2, number):
        if number % i == 0:
            divisors.append(i)
    
    return sum(divisors) == number

limit = 1000
perfect_numbers = [num for num in range(2, limit + 1) if is_perfect_number(num)]

print("1000以内的完数:", perfect_numbers)
def find_perfect_numbers(limit):
    perfect_numbers = []

    for num in range(2, limit + 1):
        divisors = [1]  # 1 is always a divisor
        for i in range(2, num):
            if num % i == 0:
                divisors.append(i)

        if sum(divisors) == num:
            perfect_numbers.append(num)

    return perfect_numbers


limit = 1000
perfect_numbers = find_perfect_numbers(limit)
print("1000以内的完数:", perfect_numbers)

结果

1000以内的完数: [6, 28, 496]

你可能感兴趣的:(python,开发语言)