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

Count Composite Numbers

Count composite integers in a supplied interval with Python. Students require a number above one before negating a prime test and avoid calling one composite.

IntermediatePhase 6 - Category 3: Loop & Conditional MixExample 3 of 10
count-composite-numbers.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# Count composites
15count = 0
16for num in range(a, b + 1):
17 if num > 1 and not is_prime(num):
18 count += 1
19
20print(f"Composite numbers: {count}")

Output

Enter start: 1
Enter end: 20
Composite numbers: 11

In this one

  • Define composite correctly
  • Reject one and negatives
  • Count rather than total

How it works

  1. 1

    Visit the inclusive entered interval.

  2. 2

    Require num above one and not prime.

  3. 3

    Increment count per composite and print.

Edge cases

Is one composite?

Is one composite?

No. The num > 1 guard excludes it.

Are negative numbers counted?

Are negative numbers counted?

No. They fail the domain guard.

What's going on

A composite number is a positive integer greater than one that is not prime. Both parts appear in num > 1 and not is_prime(num).

The helper alone returning false is insufficient because zero, one, and negatives are not composite. Every qualifying interval entry increments count by one. This is a count, not a sum, and the inclusive range keeps both endpoints eligible.

Is one composite? No. The num > 1 guard excludes it.

Are negative numbers counted? No. They fail the domain guard.

Quiz

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

Question 1

Why not use not is_prime alone?

Pick an answer to check it.

Question 2

Is one composite?

Pick an answer to check it.

Questions people ask

Is one composite?

No. The num > 1 guard excludes it.

Are negative numbers counted?

No. They fail the domain guard.

Why not use not is_prime alone?

It would also accept values below two.