Placement Prep

Python Program to Print Prime Numbers in a Range

Step-by-step Python programs to print prime numbers in a range. Covers trial division, Python's for/else idiom, and the Sieve of Eratosthenes.

By FACE Prep Team 5 min read
python prime-numbers coding-practice placement-prep algorithms programming

A prime number has exactly two divisors, 1 and itself, which makes 2 the only even prime and puts 1 outside the prime category entirely.

Placement coding rounds at IT service companies use prime-number problems to test loop control, modular arithmetic, and Python’s for/else construct. This article covers two implementations: a trial-division method that works for any range and a Sieve of Eratosthenes for larger upper bounds.

What makes a number prime

A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. Two edge cases trip up students in coding rounds more often than the main algorithm does.

The first: 1 is not prime. The definition requires exactly two distinct divisors. One has only one divisor (itself), so it fails the condition. Code that starts its range check at 1 will incorrectly print 1 as a prime.

The second: 2 is prime and is the only even prime. Every even number greater than 2 is divisible by 2, which gives it a third divisor and makes it composite.

All prime numbers up to 30:

  • 2, 3, 5, 7, 11, 13, 17, 19, 23, 29

Composite numbers in the same range include 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, and 30. Each has at least one divisor beyond 1 and itself.

Algorithm: why checking to the square root is enough

The naive approach tests every integer from 2 to n-1 for divisibility. That is O(n) operations per candidate. The standard optimisation stops at the square root of n.

The reasoning: if n is composite, it can be written as n = a times b where both a and b are greater than 1. If both factors were larger than the square root of n, their product would exceed n. So at least one factor must be less than or equal to the square root. Checking divisors up to sqrt(n) is therefore sufficient.

A concrete example: for n = 35, the square root is roughly 5.9. The factors are 5 and 7. The algorithm finds 5 immediately, breaks, and correctly labels 35 as composite without ever reaching 6, 7, 8, or 34.

Python 3’s math.isqrt(n) computes the integer square root without floating-point rounding errors. The correct upper bound for the inner loop is math.isqrt(num) + 1 so that range() includes the square root itself.

Python code to print prime numbers in a range

import math

low = int(input("Enter lower range: "))
high = int(input("Enter upper range: "))

for num in range(low, high + 1):
    if num < 2:
        continue
    for i in range(2, math.isqrt(num) + 1):
        if num % i == 0:
            break
    else:
        print(num, end=" ")

Sample run:

Enter lower range: 3
Enter upper range: 15
3 5 7 11 13

The output matches the expected sequence. All five numbers are prime and no composite in the range 3 to 15 appears in the output. The if num < 2: continue guard handles lower bounds of 0 or 1 without a separate pre-check.

How Python’s for/else handles prime detection

Python’s for/else is one of the language’s lesser-known constructs. The else clause on a for loop runs when the loop body completes normally, without hitting a break statement.

In the prime checker:

  • The inner loop runs i from 2 to math.isqrt(num) inclusive.
  • If num % i == 0 for any i, a divisor exists and the loop breaks. The else clause does not run.
  • If the loop finishes without finding a divisor, the else clause executes and prints the number.

The flag-variable alternative produces the same result but is more verbose:

import math

low = int(input("Enter lower range: "))
high = int(input("Enter upper range: "))

for num in range(low, high + 1):
    if num < 2:
        continue
    is_prime = True
    for i in range(2, math.isqrt(num) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        print(num, end=" ")

Both produce identical output. The for/else version removes the temporary boolean. Placement coding judges accept either approach, but knowing the for/else idiom is useful when interviewers ask about Python-specific features.

The same digit-extraction and modular-arithmetic loop pattern appears in the Armstrong number check. Solving one makes the other easier to write from memory.

Sieve of Eratosthenes: faster prime generation in Python

Trial division checks each candidate independently. The Sieve of Eratosthenes works differently: it pre-marks all composite numbers in a single pass over a boolean array.

The algorithm:

  • Create a boolean list sieve of length high + 1, all initialised to True.
  • Set sieve[0] and sieve[1] to False.
  • For each index i starting at 2, if sieve[i] is still True, mark all multiples of i from i * i onward as False.
  • Iterate only to math.isqrt(high). Composites above that point are already marked by smaller primes.
  • Collect all indices still True in the range [max(2, low), high].
import math

def primes_in_range(low, high):
    if high < 2:
        return []
    sieve = [True] * (high + 1)
    sieve[0] = sieve[1] = False
    for i in range(2, math.isqrt(high) + 1):
        if sieve[i]:
            for j in range(i * i, high + 1, i):
                sieve[j] = False
    return [n for n in range(max(2, low), high + 1) if sieve[n]]

low = int(input("Enter lower range: "))
high = int(input("Enter upper range: "))
print(*primes_in_range(low, high))

Same output for range 3 to 15: 3 5 7 11 13.

The sieve runs in O(N log log N) time. Trial division over the same range takes O(N sqrt(N)). For the upper bounds common in placement-round problems, both methods finish well within time limits. The sieve becomes the better choice when the upper bound is large enough that allocating the boolean array is faster than running independent divisibility checks for every candidate.

Prime problems in placement coding rounds

Placement coding rounds present prime-number problems in several forms beyond the basic range printer:

  • Prime check: given a single number, return whether it is prime. This is the inner logic from the range program, extracted into a function.
  • Twin primes: find all pairs where both n and n+2 are prime. Examples: (3, 5), (5, 7), (11, 13), (17, 19).
  • Prime factorisation: express a number as a product of prime factors. Requires repeated trial division starting from 2.
  • Goldbach partition: check whether a given even number can be written as a sum of two primes.

The underlying algorithm is the same across all four variants. What changes is the output format and how the range or target is supplied. The skill being assessed is whether the code handles early termination correctly and avoids the 1-is-not-prime and even-number edge cases.

Two tips for timed rounds:

  • Write the if num < 2: continue guard before the inner loop, not inside it. Some test judges include 0 or 1 in the range.
  • If the problem provides no memory constraint and the range is fixed, the sieve is faster and avoids per-number overhead.

The full collection of comparable Python problems is at Python practice programs.

The loop-control discipline in the sieve above (marking composites early and stopping the inner loop on the first found divisor) is the kind of algorithmic thinking placement rounds reward. If you want to apply that same precision to Python code that calls real LLM APIs, TinkerLLM is the next step, starting at ₹299.

Primary sources

Frequently asked questions

Is 1 a prime number?

No. A prime must be greater than 1 and have exactly two divisors: 1 and itself. The number 1 has only one divisor, so it does not qualify. Forgetting this edge case is a common error in placement coding submissions.

Is 2 prime, and why is it the only even prime?

Yes, 2 is prime. It is the only even prime because every even number greater than 2 is divisible by 2, giving it a third divisor and making it composite. The trial-division code skips numbers below 2 with a continue statement, so 2 is handled correctly.

What does Python's for/else construct do in the prime checker?

The else clause on a for loop runs only when the loop completes without hitting a break. In the prime checker, break fires whenever a divisor is found. If no divisor is found the else clause runs and identifies the number as prime, removing the need for a separate boolean flag.

What is the time complexity of the trial-division prime check?

O(sqrt(n)) per number. For a range from low to high the overall complexity is O((high minus low) multiplied by sqrt(high)). The Sieve of Eratosthenes improves on this by reducing the total work to O(N log log N) for all primes up to N, where N is the upper bound.

When do prime-number problems appear in placement coding rounds?

Prime checking appears as a standalone range printer, as a sub-step in factorisation or GCD problems, and in variants like twin primes and Goldbach partitions. The skill being tested is loop control and early-exit logic, not a memorised formula.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF