Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

Python Program to Check a Prime Number

A simple Python program checks divisors through the integer square root to determine whether an integer is prime.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use trial division to test whether an integer is prime: reject values below 2, then check whether any integer from 2 through the square root divides it evenly. This beginner-friendly Python function uses math.isqrt for an exact integer bound.

Python program to check if a number is prime

Copy and run this program in Python 3.8 or later:

from math import isqrt

def is_prime(n: int) -> bool:
    if n < 2:
        return False

    for divisor in range(2, isqrt(n) + 1):
        if n % divisor == 0:
            return False

    return True

number = int(input("Enter an integer: "))
if is_prime(number):
    print(f"{number} is prime")
else:
    print(f"{number} is not prime")

The function returns True for a prime number and False otherwise. The final lines read an integer from the user and print the result.

Why the test only checks through the square root

A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. If a number has a factor greater than its square root, it must also have a matching factor smaller than its square root. Checking possible divisors up to that boundary is therefore enough to find any nontrivial factor.

n % divisor == 0 checks whether division leaves no remainder. When it does, the function has found a divisor and returns False. If the loop finishes without finding one, it returns True.

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

range excludes its stop value, so isqrt(n) + 1 makes the loop include the integer square root when it is an exact square. Python’s math documentation defines isqrt as returning the integer square root of a nonnegative integer; it avoids using a floating-point square root to set the bound.

How the program handles edge cases

  • Negative integers, 0, and 1: the n < 2 check returns False, since none is prime.
  • 2: the divisor range is empty, so the function returns True.
  • A composite number such as 18: the first divisor, 2, divides it evenly, so the function returns False.
  • A prime number such as 17: no tested divisor divides it evenly, so the function returns True.

Python version and input considerations

math.isqrt was added in Python 3.8. For an interpreter older than Python 3.8, use a compatible integer-bound method or update Python before running this version. The official Python documentation page links to the Beginner’s Guide and Tutorial for help getting started.

The sample converts input with int(input(...)). If the user enters text that is not an integer, Python raises ValueError; this short example does not catch that exception.

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

When this method fits

Trial division through the integer square root is a clear approach for checking one number in a beginner exercise. It is not presented as an optimal primality test for cryptographic-scale integers, and no runtime comparison is established here. If the task is instead to find every prime up to a fixed maximum, that is a different problem and a sieve may be a better fit; no measured crossover point is established.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

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.

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

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.