8-6.素因子分解。以刚才练习中的isprime()和getfactors()函数为基础编写一个函数,它接受一个整型作为参数,返回该整型所有素数因子的列表。这个过程叫做求素因子分解,它输出的所有因子之积应该是原来的数字。注意列表里可能有重复的元素。例如输入20,返回的结果应该是[2,2,5]。
【答案】代码如下:def isprime(number): switch = True if number <= 1: switch = False for i in range(2, number / 2 + 1): if number % i == 0: switch = False return switchdef getfactors(number): factorList = [] for i in range(1, number + 1): if number % i == 0 and isprime(i): factorList.append(i) return factorList def findPrimeFactors(number): temp = getfactors(number) k = 1 for i in temp: k = k * i if k == number: return temp else: j = number / k return temp + findPrimeFactors(j) number = int(raw_input("Please input your number ... ")) if isprime(number): print "You have already input a prime number."else: factors = findPrimeFactors(int(number)) factors.sort() print factors 【执行结果】
Please input your number ... 199876[2, 2, 107, 467]Please input your number ... 7099092[2, 2, 3, 3, 7, 11, 13, 197]Please input your number ... 197You have already input a prime number.Please input your number ... 20[2, 2, 5]
8-7.完全数。完全数被定义为这样的数字:它的约数(不包括它自己)之和为它本身。例如:6的约数是1,2,3,因为1+2+3=6,所以6被认为是一个完全数。编写一个名为isperfect()的函数,它接受一个整形作为参数,如果这个数字是完全数,返回1:否者返回0。
【答案】代码如下:def getfactors(number): factorList = [] for i in range(1, number): if number % i == 0: factorList.append(i) return factorListdef isperfect(number): if sum(getfactors(number)) == number: return True else: return False number = raw_input("Please input your number ... ")print number, getfactors(int(number)), isperfect(int(number))
def factorial(number): k = 1 for i in range(1, number+1): k = k*i return knumber = raw_input("Please input your number ... ")print factorial(int(number))