一个数如果恰好等于它的所有因子(不包括它自己)之和,就称其为完数,比如6=1+2+3。输出n之内的全部“完数”,n从键盘上输入。这里保证输入的n值是正整数,读者无需考虑。 输出中,每个数占的宽度为6,
时间: 2024-12-10 09:34:11 浏览: 8
为了编写这样一个程序,你需要使用一个循环结构遍历指定范围内的数字,并检查它们是否是完数。以下是Python的一个简单实现:
```python
def find_perfect_numbers(n):
perfect_numbers = []
for num in range(1, n + 1):
sum_factors = 1 # 1 always counts as a factor of any number
i = 2
while i * i <= num:
if num % i:
i += 1
else:
num //= i
sum_factors += i
if num > 1: # check if the remaining number is also a factor (if it's greater than 1)
sum_factors += num
if sum_factors == num: # check if it's a perfect number
perfect_numbers.append(str(num).zfill(6)) # pad with zeros to ensure width of 6
return perfect_numbers
# 获取用户输入的n
n = int(input("请输入一个正整数n: "))
# 输出n内的完美数
perfect_nums = find_perfect_numbers(n)
print("范围 {} 内的完美数有:".format(n))
for num in perfect_nums:
print(num)
阅读全文