python编译1000以内的完数,输出为完数,以及完数的约数
时间: 2023-06-07 13:09:28 浏览: 130
以下是实现完数、输出完数、完数的约数的Python代码:
```python
def find_perfect_numbers(num):
"""
寻找num以内所有的完数
"""
perfect_nums = []
for i in range(1, num):
divisor_sum = sum([j for j in range(1, i) if i % j == 0]) # 寻找i的因子之和
if divisor_sum == i:
perfect_nums.append(i)
return perfect_nums
def find_factors(num):
"""
寻找num的所有的约数
"""
factors = []
for i in range(1, num+1):
if num % i == 0:
factors.append(i)
return factors
if __name__ == '__main__':
# 找到1000以内所有的完数
perfect_nums = find_perfect_numbers(1000)
print(f"1000以内的完数为:{perfect_nums}")
# 打印每个完数以及它的约数
for perfect_num in perfect_nums:
factors = find_factors(perfect_num)
print(f"{perfect_num}的约数为:{factors}")
```
输出结果:
```
1000以内的完数为:[6, 28, 496]
6的约数为:[1, 2, 3, 6]
28的约数为:[1, 2, 4, 7, 14, 28]
496的约数为:[1, 2, 4, 8, 16, 31, 62, 124, 248, 496]
```
阅读全文