Python练习100例-19

一个数如果恰好等于它的因子之和,这个数就称为”完数”。例如6=1+2+3.

练习代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

while True:
    try:
        num=input('请输入数字:')
        num=int(num)
        break
    except ValueError :
        print('您输入的是非法字符,请重新输入!')

def factor(n):
    for i in range(2,n):
        s=n/i
        if int(s)==s:
            return str(i)+'*'+str(factor(int(s)))
    return str(n)

def isperfect(num):
    sum=0
    sum1=''
    factorization='1*'+factor(num)
    f=factorization.split('*')
    for n in f:
        sum=sum+int(n)
        sum1=sum1+n+'+'
    print('%d=%s'%(num,factorization))
    print('%d=%s'%(sum,sum1[0:len(sum1)-1]))
    if sum==num:
        return True
    else:
        return False

print('%d是否是完数:%s'%(num,isperfect(num)))

你可能感兴趣的:(python练习,python)