Home » Python programs

Python program to find perfect number

Checking perfect number: What is perfect number? How to check whether a given number is perfect number of not in Python?
Submitted by Ankit Rai, on July 25, 2019

Given an integer number and we have to check whether it is perfect number or not?

This Python program is used to find its all positive divisors excluding that number.

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.

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

Python code to find perfect number

if __name__ == "__main__" :

    # initialisation 
    i = 2;sum = 1;

    # take input from user and typecast into integer
    n = int(input("Enter a number: "))

    # iterating till n//2 value
    while(i <= n//2 ) :

        # if proper divisor then add it.
        if (n % i == 0) :

            sum += i

        i += 1

    # check sum equal to n or not
    if sum == n :
        print(n,"is a perfect number")

    else :
        print(n,"is not a perfect number")
       

Output

First run:
Enter a number: 28
28 is a perfect number

Second run:
Enter a number: 14
14 is not a perfect number





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.