一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如 6=1+2+3.编程找出 1000 以内的所有完数。
perfect_number_list = [] for perfect_number in range(2, 1000): # 找出一个数的所有因子,加入到因数列表里 factor_list = [] for factor in range(1, perfect_number): if perfect_number % factor == 0: factor_list.append(factor) # 求出这个数的因子之和,用summing表示 summing = 0 for i in range(len(factor_list)): summing += factor_list[i] # 判断这个数和因子之和是否相等 if perfect_number == summing: perfect_number_list.append(perfect_number) for i in range(len(factor_list)): if i == 0: print(f'{perfect_number} = {factor_list[i]}', end='') if 0 < i <= len(factor_list) - 1: print(f'+{factor_list[i]}', end='') print('\n') print(f'1000以内的所有完数有:{perfect_number_list}')
标签:perfect,编程,list,number,range,完数,factor,1000 From: https://www.cnblogs.com/sangern/p/17404503.html