Count Composite Numbers

Count composite numbers in range.

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

What's going on

Count numbers that are not prime.

Key Concepts:

Composite = not prime and > 1
Check each number
Count composites