A number is called a perfect number if it is equal to the sum of all of its divisors, not including
the number itself. For instance, 6 is a perfect number because the divisors of 6 are 1, 2, 3, 6
and 6 = 1 + 2 + 3. As another example, 28 is a perfect number because its divisors are 1, 2, 4,
7, 14, 28 and 28 = 1 + 2 + 4 + 7 + 14. However, 15 is not a perfect number because its divisors
are 1, 3, 5, 15 and 15 ̸= 1 + 3 + 5. Write a program that finds all four of the perfect numbers
that are less than 10000.
# initialize a list to store the perfect numbers
perfect_numbers = []
# loop through the numbers from 1 to 10000
for number in range(1, 10001):
# initialize the sum of the divisors to 0
divisor_sum = 0
# loop through the numbers from 1 to the number
for i in range(1, number):
# check if i is a divisor of the number
if number % i == 0:
# if it is, add it to the sum of the divisors
divisor_sum += i
# check if the number is a perfect number
if divisor_sum == number:
# if it is, add it to the list of perfect numbers
perfect_numbers.append(number)
# print the list of perfect numbers
print(perfect_numbers)
This program first initializes a list to store the perfect numbers. It then loops through the numbers from 1 to 10000, and for each number it initializes a divisor_sum
variable to 0 and loops through the numbers from 1 to the number, adding the divisors to the divisor_sum
. It then checks if the divisor_sum
is equal to the number, and if it is, it adds the number to the list of perfect numbers. Finally, it prints the list of perfect numbers.
If you run the program, it will find and print all four of the perfect numbers that are less than 10000. For example, you might see something like:
[6, 28, 496, 8128]
0 Comments