Python Program to Generate Perfect Numbers in an Interval
This python program generates perfect numbers in an interval given by user.
A perfect number is a positive integer number in which sum of all positive divisors excluding the number itself is equal to that number.
Perfect Number Example: 6 is perfect number since its divisors are 1, 2, and 3. Sum of divisors is: 1+2+3 = 6.
Also try: Check Perfect Number Online & Generate Perfect Numbers Online
Python Source Code: Generate Perfect Numbers
# Generate Perfect numbers in interval
# Function to check perfect number
def is_perfect(n):
if n< 1:
return False
perfect_sum = 0
for i in range(1,n):
if n%i==0:
perfect_sum += i
return perfect_sum == n
# Reading interval from user
min_value = int(input('Enter minimum value: '))
max_value = int(input('Enter maximum value: '))
# Looping & displaying if it is Perfect
# Here min_vale & max_value are included
print('Perfect numbers from %d to %d are:' %(min_value, max_value))
for i in range(min_value, max_value+1):
if is_perfect(i):
print(i, end=' ')
Perfect Number Generation: Output
Perfect numbers from -10 to 100000 are: 6 28 496 8128
Perfect Number Generation: Code Explanation
We first read min_value and max_value from user. Function is_perfect()
is used to check whether a given number is perfect or not. We loop from min_value
to max_value
and pass each number to is_perfect()
function. If this function returns True
, then we print it.