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.
1# Helper function2def is_prime(n):3 if n < 2:4 return False5 for i in range(2, int(n ** 0.5) + 1):6 if n % i == 0:7 return False8 return True910# Take range11a = int(input("Enter start: "))12b = int(input("Enter end: "))1314# Count composites15count = 016for num in range(a, b + 1):17 if num > 1 and not is_prime(num):18 count += 11920print(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
Visit the inclusive entered interval.
- 2
Require num above one and not prime.
- 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.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum