Python程序从给定的整数列表中打印完美数字

Given a list of the integer numbers and we have to print all perfect numbers present in the given list.

给定一个整数列表,我们必须打印给定列表中存在的所有正整数。

This Program iterating through each number one by one in the list, and check whether a given number is a perfect number or not. If a perfect number is found then print it else skip it.

该程序逐个迭代列表中的每个数字,并检查给定的数字是否为理想数字 。 如果找到一个完美的数字,则打印它,否则跳过它。

In this program, checkPerfectNum() function is used to find its all positive divisors excluding that number and sum it all and then check for perfect number condition.

在此程序中,使用checkPerfectNum()函数查找除该数字外的所有正数,然后将其全部求和,然后检查理想的数字条件。

Explanation: For Example, 28 is a perfect number since divisors of 28 are 1, 2, 4,7,14 then sum of its divisor is 1 + 2 + 4 + 7 + 14 = 28.

说明:例如,28是一个完美数字,因为28的除数是1、2、4、7、14,然后其除数之和是1 + 2 + 4 + 7 + 14 = 28。

Note: A perfect number is a positive integer that is equal to the sum of its proper positive divisors.

注意:理想数是一个正整数,等于其适当的正因数之和。

Python代码从给定的整数列表中打印完美数字 (Python code to print perfect numbers from the given list of integers)

# Define a function for checking perfect number
# and print that number
def checkPerfectNum(n) :
	# initialisation 
	i = 2;sum = 1;

	# iterating till n//2 value
	while(i <= n//2 ) :
		# if proper divisor then add it.
		if (n % i == 0) :
			sum += i			
		
		# incrementing i by one
		i += 1
		
		# check sum equal to n or not
		if sum == n :
			print(n,end=' ')

# Main code
if __name__ == "__main__" :

	# take list of number as an input from user 
	# and typecast into integer
	print("Enter list of integers: ")
	list_of_intgers = list(map(int,input().split()))

	print("Given list of integers:",list_of_intgers)

	print("Perfect numbers present in the list is: ")
	# Iteration through the each element of 
	# the list one by one
	for num in list_of_intgers :
		# function call
		checkPerfectNum(num)

Output

输出量

Enter list of integers:
14 20 6 78 28
Given list of integers: [14, 20, 6, 78, 28]
Perfect numbers present in the list is:
6 28


翻译自: https://www.includehelp.com/python/program-to-print-perfect-numbers-from-the-given-list-of-integers.aspx