编程完数的Python题
时间: 2023-11-17 17:58:41 浏览: 73
以下是几个Python编程完数的例子:
1. 判断一个数是否为完数:
```python
def is_perfect(num):
divisors = []
for i in range(1, num):
if num % i == 0:
divisors.append(i)
if sum(divisors) == num:
return True
else:
return False
# 测试
print(is_perfect(6)) # True
print(is_perfect(28)) # True
print(is_perfect(12)) # False
```
2. 找到1000以内的所有完数:
```python
def find_perfect_numbers():
perfect_numbers = []
for num in range(1, 1001):
if is_perfect(num):
perfect_numbers.append(num)
return perfect_numbers
# 测试
print(find_perfect_numbers()) # [6, 28, 496]
```
3. 找到指定范围内的所有完数:
```python
def find_perfect_numbers(start, end):
perfect_numbers = []
for num in range(start, end+1):
if is_perfect(num):
perfect_numbers.append(num)
return perfect_numbers
# 测试
print(find_perfect_numbers(1, 1000)) # [6, 28, 496]
print(find_perfect_numbers(1, 10000)) # [6, 28, 496, 8128]
```
阅读全文