每日一程-12.Python-寻找完全数

Author: Notus([email protected])
Create: 2019-02-19
Update: 2019-02-19

Python 寻找完全数

环境

Python version: 3.7.1

代码如下

'''
    寻找完全数: 判断输入的数是否是完全数。
    完全数:是一个整数,其因数的和(不含本身)加起来就是数字本身,如
    28 = 1 + 2 + 4 + 7 + 14
    测试: 6, 28, 496, 8128 都是完全数
    @Author: Notus([email protected])
    @Create: 2019-02-19
    @Update: 2019-02-19
    @Version: 0.1
'''

import sys

theNum = input('请输入一个数:')

try:
    theNum = int(theNum)
except ValueError:
    print("请输入一个整数!")
    sys.exit()

# 因子
divisor = 1
# 因子的和
divisors = 0

# 求因子的和
while divisor < theNum:
    if theNum % divisor == 0:
        divisors += divisor
    divisor += 1

if divisors == theNum:
    print("{} 是完全数!\n".format(theNum))
else:
    print("{0} 不是完全数!\n".format(theNum))

运行结果

C:\Users\Notus\Desktop>python a.py
请输入一个数:99
99 不是完全数!


C:\Users\Notus\Desktop>python a.py
请输入一个数:
请输入一个整数!

C:\Users\Notus\Desktop>python a.py
请输入一个数:28
28 是完全数!


C:\Users\Notus\Desktop>

猜你喜欢

转载自www.cnblogs.com/leo1875/p/10403965.html