Count Prime Numbers

Count prime numbers in array.

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

What's going on

Check each element for primality.

Key Concepts:

Use helper function to check prime
Count elements that are prime
Filter and count