Home > Python > Basic Python Programs

Ch. 3.2 Determining Whether an Integer is Prime or Not

Chapters Index
Program 1

Determining Whether an Integer is Prime or Not

Python 3.11 Ready

                                
Click "Run Code" to execute script and render figures.

Mathematical Problem Formulation

Input:

Given number \( n \) (e.g., \( n = 49 \)).

Check if \( n < 2 \):

If \( n \) is less than 2, return 'not prime'. (This is because prime numbers are defined as greater than 1.)

Initialize Loop:

Loop through all integers \( i \) from 2 to the integer value of the square root of \( n \) (inclusive). This is done using the range:

for i in range(2, int(n**0.5) + 1)

Check for Divisibility:

For each \( i \) in the loop:

If \( n \) is divisible by \( i \) (i.e., if \( n \mod i == 0 \)): return 'not prime'. (This means that \( n \) has a divisor other than 1 and itself.)

Return Result:

If no divisors were found in the loop, return 'prime'.

Output:

Call the prime(n) function and print the result.

Example Walkthrough

For \( n = 49 \):

  • Check if \( 49 < 2 \): False (continue to next step).
  • Loop through \( i = 2 \) to \( 7 \) (the square root of \( 49 \) is \( 7 \)):
    • i = 2: \( 49 \mod 2 \neq 0 \) (continue).
    • i = 3: \( 49 \mod 3 \neq 0 \) (continue).
    • i = 4: \( 49 \mod 4 \neq 0 \) (continue).
    • i = 5: \( 49 \mod 5 \neq 0 \) (continue).
    • i = 6: \( 49 \mod 6 \neq 0 \) (continue).
    • i = 7: \( 49 \mod 7 = 0 \) (return 'not prime').