Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Primes in Range

Count primes in an inclusive interval with nested loops. Students skip candidates below two, stop factor checks early, and increment a count only for primes.

AdvancedPhase 2 - Level 5: Logical Loop CombinationsExample 12 of 12
count-primes-in-range.py
1# Take range
2a = int(input("Enter start: "))
3b = int(input("Enter end: "))
4
5# Count primes
6count = 0
7for num in range(a, b + 1):
8 if num < 2:
9 continue
10 is_prime = True
11 for i in range(2, int(num ** 0.5) + 1):
12 if num % i == 0:
13 is_prime = False
14 break
15 if is_prime:
16 count += 1
17
18print(f"Primes in range: {count}")

Output

Enter start: 10
Enter end: 30
Primes in range: 6

In this one

  • Separate candidate and factor searches
  • Skip nonprime domains
  • Count only successful classifications

How it works

  1. 1

    Visit the inclusive entered interval.

  2. 2

    Skip values below two; test remaining factors.

  3. 3

    Increment count only for candidates still marked prime.

Edge cases

What if the interval starts negative?

What if the interval starts negative?

Values below two are skipped safely.

What if start exceeds end?

What if start exceeds end?

The range is empty and the count is zero.

What's going on

The outer range includes both entered endpoints. continue skips values below two before attempting a square-root divisor search.

Each remaining candidate receives a fresh is_prime flag. A factor clears it and breaks the inner loop; only surviving candidates increment count. Unlike the prime-list exercise, the program reports how many primes were found rather than printing their values.

What if the interval starts negative? Values below two are skipped safely.

What if start exceeds end? The range is empty and the count is zero.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Does break end the outer loop?

Pick an answer to check it.

Question 2

What if the interval starts negative?

Pick an answer to check it.

Questions people ask

What if the interval starts negative?

Values below two are skipped safely.

What if start exceeds end?

The range is empty and the count is zero.

Does break end the outer loop?

No, only the divisor loop.