Counting Prime Numbers

Category: Python Basics

Write a program that counts the number of prime numbers less than a given number. The program should take an integer as input and output the number of primes less than the input.

Example:

Input: 10 

Output: 4

Input: 20 

Output: 8

A prime number is a natural number greater than 1 that has no divisors other than 1 and itself. You may need to implement a helper function to check if a number is prime.

def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

def count_primes(num):
count = 0
for i in range(2, num):
if is_prime(i):
count += 1
return count

print(count_primes(10)) # Outputs: 4
print(count_primes(20)) # Outputs: 8

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!