Count Prime Numbers
Count prime entries in a list using a helper function. Students numeric classification from traversal and understand why repeated primes count repeatedly.
1# Helper function2def is_prime(num):3 if num < 2:4 return False5 for i in range(2, int(num ** 0.5) + 1):6 if num % i == 0:7 return False8 return True910# Take array11n = int(input("Enter array size: "))12arr = []13for i in range(n):14 arr.append(int(input(f"Element {i+1}: ")))1516# Count primes17prime_count = 018for element in arr:19 if is_prime(element):20 prime_count += 12122print(f"Number of primes: {prime_count}")
Output
Enter array size: 5 Element 1: 2 Element 2: 4 Element 3: 7 Element 4: 9 Element 5: 11 Number of primes: 3
In this one
- Extract a predicate helper
- Reject nonprime domains
- Count duplicate primes separately
How it works
- 1
Define the factor-testing is_prime helper.
- 2
Call it for every array entry.
- 3
Increment prime_count for each true result.
Edge cases
Does one count?
Does one count?
No. The helper rejects numbers below two.
Does [2, 2] give one prime?
Does [2, 2] give one prime?
No. It counts two prime entries.
What's going on
is_prime rejects values below two, then tests divisors through the square-root bound. Finding any factor returns false immediately.
The outer loop calls that helper once per element and increments prime_count for true results. Repeated primes are counted separately because this counts positions, not distinct primes. An empty divisor range correctly leaves two and three prime.
Does one count? No. The helper rejects numbers below two.
Does [2, 2] give one prime? No. It counts two prime entries.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does a factor prove?
Pick an answer to check it.
Question 2
Does one count?
Pick an answer to check it.
Questions people ask
Does one count?
No. The helper rejects numbers below two.
Does [2, 2] give one prime?
No. It counts two prime entries.
What does a factor prove?
The candidate is not prime.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum