PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Programs and Examples » Python Programs to Find Perfect Number

Python Programs to Find Perfect Number

Updated on: March 31, 2025 | Leave a Comment

A Perfect Number is a positive integer equal to the sum of all its positive divisors, excluding the number itself.

Let’s say the input number is 6.

  • The divisors of 6 are 1, 2, and 3.
  • The sum of these divisors is 1 + 2 + 3 = 6.
  • Since the sum is equal to the original number, 6 is a perfect number.

This article explores different ways to find perfect numbers in Python, with explanations and examples. We’ll delve into the logic behind finding divisors, summing them efficiently, and checking for perfect number properties.

This article explores different methods, including using the modulo operator, loops, list comprehensions, and math module.

Table of contents

  • 1. How to Find a Perfect Number in Python
  • 2. Using math.sqrt function
  • 3. Using List Comprehension
  • Summary

1. How to Find a Perfect Number in Python

Below are the steps to find a perfect number in Python:

  1. Input

    Set number or take an integer number as input from the user.

  2. Initialization

    Initialize a variable divisors_sum to 0. This variable will store the sum of all proper divisors.

  3. Find divisors using loop

    Iterate through the numbers from 1 up to (but not including) number. Inside the loop, for each number in this range, check if it is a divisor of number (i.e., if number is divisible by the current number without any remainder). If a number is a divisor, add it to the divisors_sum.

  4. Check for Perfect Number

    After iterating through all potential divisors, compare the divisors_sum with the original number. If the divisors_sum is equal to number, then number is a perfect number. Otherwise, it is not a perfect number.

  5. Output

    Print a message indicating whether the input number is a perfect number or not.

Code Example

def is_perfect_square(num):
    divisors_sum = 0

    # Loop through all numbers from 1 to num - 1
    for i in range(1, num):
        if num % i == 0:  # Check if 'i' is a divisor of 'num'
            divisors_sum += i  # Add the divisor to the sum

    # Check if the sum of divisors equals the number
    return divisors_sum == num

number = 6
print(is_perfect_square(number))     # True

number = 15
print(is_perfect_square(number))    # FalseCode language: Python (python)

2. Using math.sqrt function

Now, Let’s see how to find a perfect number using a math module.

The math.sqrt() is a Python built-in function that calculates the square root of a given number. For example, math.sqrt(25) returns 5.0.

In this method, the modulo operator (%) is used to find the divisor of a number. Here, instead of checking all numbers up to n, you only need to check up to the square root of n (√n).

This method improves efficiency by only checking divisors up to the square root of the number, leveraging the fact that divisors occur in pairs.

For Example,

  • For number = 28:
    • The square root of 28 is approximately 5.29, so the loop checks divisors up to 5.
  • Divisor pairs found:
    • For i = 2, number // i = 14. Add both 2 and 14 to the sum.
    • For i = 4, number // i = 7. Add both 4 and 7 to the sum.
  • Total divisor sum: 1 + 2 + 14 + 4 + 7 = 28.
  • Since the sum equals the original number, 28 is confirmed as a perfect number.

Code Example

import math

# Input number to check
num = 28

# Initialize the sum of divisors
divisors_sum = 1  # Start with 1, as it is a divisor of every number

# Check divisors up to the square root of the number
for i in range(2, int(math.sqrt(num)) + 1):
    if num % i == 0:  # Check if 'i' is a divisor of 'num'
        divisors_sum += i
        if i != num // i:  # Avoid adding the square root twice
            divisors_sum += num // i

# Check if the sum of divisors equals the number
is_perfect = divisors_sum == num

# Output the result
print(f"Is {num} a perfect number? -> {is_perfect}")Code language: Python (python)

Output:

Is 28 a perfect number? -> TrueCode language: Python (python)

Explanation

  • Initialization: The sum of divisors starts at 1 because 1 is a divisor of every number.
  • Square Root Check: The loop runs only up to the square root of num, calculated using math.sqrt(num). This reduces unnecessary checks for numbers larger than √n.
  • Divisor Check: For each number i in the range, the modulo operator (%) checks if i is a divisor of num. If num % i == 0, it confirms that i divides num without leaving a remainder.
  • Divisor Pairs: Whenever a divisor i is found, the corresponding divisor num // i is also calculated and added to the sum. This ensures all divisor pairs are included, except when i equals num // i (to avoid duplication).
  • Comparison: After calculating the sum of divisors, it is compared with the original number. If they are equal, then it is a perfect number.

3. Using List Comprehension

List comprehension is a concise way to create Python lists by applying an expression to each item in an iterable, with optional filtering using a condition. It allows you to create a list of divisors efficiently.

The built-in sum() function is then used to calculate the total sum of the divisors in the list, enabling a concise and elegant way to determine if a number is perfect.

Code Example

# Input number to check
num = 28

# Calculate the sum of divisors using list comprehension
is_perfect = num == sum([i for i in range(1, num) if num % i == 0])

# Output the result
print(f"Is {num} a perfect number? -> {is_perfect}")Code language: Python (python)

Output:

Is 28 a perfect number? -> TrueCode language: Python (python)

Explanation

  • List Comprehension: It generates a list of all divisors of num by iterating through numbers from 1 to num-1 and including only those that divide num with reminder 0, i.e., num % i == 0.
  • sum() function: It calculates the total sum of the divisors.
  • Comparison: After calculating the sum of divisors, it is compared with the original number. If they are equal, then it is a perfect number.

Summary

Each method has its unique advantages depending on the use case.

  • For Loop:
    • Advantage: Simple and easy to understand.
    • Time Complexity: O(n) – The loop runs from 1 to num-1, performing a constant-time check for each number.
    • Space Complexity: O(1) – Only a few variables are used to store the sum and current divisor.
  • Using math.sqrt function: Best Choice
    • Advantage: Fast method. Significantly reduces iterations by leveraging divisor pairs.
    • Time Complexity: O(√n) – The loop runs up to the square root of num.
    • Space Complexity: O(1) – Uses only a few variables for the sum and divisors.
  • List Comprehension:
    • Advantage: Concise and Pythonic; combines looping and filtering in a single line.
    • Time Complexity: O(n) – Iterates through all numbers from 1 to num-1 to generate the list of divisors.
    • Space Complexity: O(n) – Creates a list of divisors, requiring additional memory to store the list.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement