编写函数,输出1000以内的所有完数及其因子。
时间: 2024-12-02 20:17:17 浏览: 15
编写一个函数来找出1000以内所有的完美数,并列出它们的所有因子是一个常见的编程练习。完美数是指它的所有真因数(除了本身之外的正因子)之和等于该数本身的数。下面是一个简单的Python示例:
```python
def find_perfect_numbers(n):
def is_divisor(num, divisor):
return num % divisor == 0
def sum_factors(num):
factors = []
for i in range(1, int(num**0.5) + 1):
if is_divisor(num, i):
factors.append(i)
if i != num // i:
factors.append(num // i)
return factors
perfects = []
for number in range(1, n+1):
factors_sum = sum_factors(number)
if factors_sum == number:
perfects.append((number, factors_sum))
return perfects
perfect_numbers = find_perfect_numbers(1000)
for perfect in perfect_numbers:
print(f"{perfect[0]}是一个完美数,其因子有:{perfect[1]}")
阅读全文