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

Sum of Primes in Range

Add all primes in an inclusive interval. Students reuse trial division and accumulate matching values rather than counting or printing each match separately.

IntermediatePhase 6 - Category 3: Loop & Conditional MixExample 2 of 10
sum-of-primes-in-range.py
1# Helper function
2def is_prime(n):
3 if n < 2:
4 return False
5 for i in range(2, int(n ** 0.5) + 1):
6 if n % i == 0:
7 return False
8 return True
9
10# Take range
11a = int(input("Enter start: "))
12b = int(input("Enter end: "))
13
14# Sum primes
15total = 0
16for num in range(a, b + 1):
17 if is_prime(num):
18 total += num
19
20print(f"Sum of primes: {total}")

Output

Enter start: 1
Enter end: 10
Sum of primes: 17

In this one

  • Filter before adding
  • Search both interval endpoints
  • Keep an empty sum

How it works

  1. 1

    Initialize total zero.

  2. 2

    Visit a through b and test each value for primality.

  3. 3

    Add prime values and print the completed sum.

Edge cases

What if start exceeds end?

What if start exceeds end?

The loop is empty and total remains zero.

Are endpoints included?

Are endpoints included?

Yes. Both can contribute if prime.

What's going on

The outer loop visits a through b. is_prime classifies each candidate, and a successful candidate is added to total.

For two through five, the result is ten from two, three, and five. Negative candidates and one are rejected by the helper's first test. A reversed interval gives an empty range and zero, not an automatically reordered search.

What if start exceeds end? The loop is empty and total remains zero.

Are endpoints included? Yes. Both can contribute if prime.

Quiz

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

Question 1

What is added after a match?

Pick an answer to check it.

Question 2

What if start exceeds end?

Pick an answer to check it.

Questions people ask

What if start exceeds end?

The loop is empty and total remains zero.

Are endpoints included?

Yes. Both can contribute if prime.

What is added after a match?

The prime value.