October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Write a Program to Find a Perfect Number in Python

A perfect number equals the sum of its proper divisors. Use Python’s modulo operator to test one number or list perfect numbers below a limit.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A perfect number equals the sum of its positive divisors other than itself. In Python, test that definition by adding divisors that divide the number evenly with the integer remainder operator %, then compare the sum with the number.

What is a perfect number?

A perfect number is equal to the sum of its proper divisors: its positive divisors excluding the number itself. Euclid’s Elements, Book VII, Definition 22, describes a perfect number as “that which is equal to the sum its own parts.”

For example, 6 has proper divisors 1, 2, and 3, and 1 + 2 + 3 = 6. The proper divisors of 28 are 1, 2, 4, 7, and 14; their sum is 28. The first four perfect numbers are 6, 28, 496, and 8128 (Euclid’s Elements, Book VII, Definition 22).

Beginner Python program to test one number

This function checks each possible proper divisor from 1 up to, but not including, the number. The modulo operator % gives the remainder; a remainder of zero means the divisor divides evenly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def is_perfect(n):
    if n <= 0:
        return False

    divisor_sum = 0
    for divisor in range(1, n):
        if n % divisor == 0:
            divisor_sum += divisor

    return divisor_sum == n

number = 28
if is_perfect(number):
    print(number, "is perfect")
else:
    print(number, "is not perfect")

The function rejects non-positive inputs because the definition here concerns positive divisors of a positive integer. For 1, the loop has no values and the proper-divisor sum is 0, so it correctly returns False. Use % rather than / for the divisibility test: Python’s / operator returns a floating-point result, while the remainder test directly determines whether division is exact. Indentation matters because it groups the statements inside the function, loop, and condition (Python tutorial: An informal introduction to Python).

List perfect numbers below a limit

To search a range, call the test for each candidate. This example treats limit as exclusive: it checks numbers from 1 through limit - 1, not the limit itself.

def perfect_numbers_below(limit):
    results = []
    for candidate in range(1, limit):
        if is_perfect(candidate):
            results.append(candidate)
    return results

print(perfect_numbers_below(10_000))

Expected output:

[6, 28, 496, 8128]

The exercise of listing the first four perfect numbers appears in a Python teaching manual (Python programming exercises). Searching below 10,000 finds exactly these four.

Check the result by hand

Verifying both positive and negative cases helps catch errors such as including the number itself in the divisor sum.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • 6: proper divisors are 1, 2, and 3; their sum is 6, so the function returns True.
  • 28: proper divisors are 1, 2, 4, 7, and 14; their sum is 28, so the function returns True.
  • 12: proper divisors are 1, 2, 3, 4, and 6; their sum is 16, so the function returns False.

Optional optimization: check divisor pairs

The full scan is easiest to understand, but for larger candidates you can check only as far as the integer square root. Divisors come in pairs: if d divides n, then n // d is the paired divisor. For example, for 28, checking 2 reveals the pair 14.

from math import isqrt

def is_perfect_fast(n):
    if n <= 1:
        return False

    divisor_sum = 1
    for divisor in range(2, isqrt(n) + 1):
        if n % divisor == 0:
            paired_divisor = n // divisor
            divisor_sum += divisor
            if paired_divisor != divisor:
                divisor_sum += paired_divisor

    return divisor_sum == n

The initial sum of 1 accounts for 1 as a proper divisor of every candidate greater than 1. The equality check on the pair prevents counting a square root twice: when n is a square and divisor equals its paired quotient, add it only once. This approach requires fewer divisibility checks as the candidate grows, but no measured timing comparison is implied; the straightforward scan is usually clearer for a first exercise.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why the first four numbers have this pattern

There is also a number-theory characterization for even perfect numbers: if 2^n - 1 is prime, then 2^(n - 1)(2^n - 1) is an even perfect number. For instance, using n = 3 gives 28 because 2^3 - 1 = 7 is prime. This is a useful explanation for a pattern, not a replacement for the program’s divisor-sum test (Number Theory in Context and Interaction).

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.