Count Prime Numbers

Count prime numbers in array.

Logic BuildingIntermediate
Logic Building
# Helper function
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

# Take array
n = int(input("Enter array size: "))
arr = []
for i in range(n):
    arr.append(int(input(f"Element {i+1}: ")))

# Count primes
prime_count = 0
for element in arr:
    if is_prime(element):
        prime_count += 1

print(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

Check each element for primality.

Key Concepts:

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