深度阅读

How to find perfect number in Python

作者
作者
2023年08月22日
更新时间
10.13 分钟
阅读时间
0
阅读量

To find if a number is a perfect number in Python, you can add all of its proper positive divisors (except the number itself) and check if the sum is equal to the number. Here’s an example program in Python:

num = int(input("Enter any positive integer: "))
sum = 0

for i in range(1, num):
    if num % i == 0:
        sum += i

if sum == num:
    print(num, "is a perfect number")
else:
    print(num, "is not a perfect number")

In this program, we prompt the user to enter a positive integer and convert the input to an integer using the int() function. Then we use a for loop to iterate through all numbers from 1 to num - 1. For each number, we check if it’s a divisor of num using the % operator. If it is, we add it to the sum variable. Finally, we check if sum is equal to num, and print the appropriate message to the console.

You can also modify the program to check a range of numbers by using another for loop to iterate through the range of numbers you want to check.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。