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

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.

IntermediatePhase 4 - Level 2: Searching & Counting LogicExample 8 of 10
count-prime-numbers.py
1# Helper function
2def is_prime(num):
3 if num < 2:
4 return False
5 for i in range(2, int(num ** 0.5) + 1):
6 if num % i == 0:
7 return False
8 return True
9
10# Take array
11n = int(input("Enter array size: "))
12arr = []
13for i in range(n):
14 arr.append(int(input(f"Element {i+1}: ")))
15
16# Count primes
17prime_count = 0
18for element in arr:
19 if is_prime(element):
20 prime_count += 1
21
22print(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. 1

    Define the factor-testing is_prime helper.

  2. 2

    Call it for every array entry.

  3. 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.