w3resource

Python: Count the number of prime numbers less than a given non-negative number


Prime Count Below n

Write a Python program that counts the number of prime numbers that are less than a given non-negative number.

Sample Solution:

Python Code:

# Function to count prime numbers up to a given limit 'n'
def count_Primes_nums(n):
    ctr = 0  # Counter to store the number of prime numbers
    
    # Iterate through numbers up to 'n'
    for num in range(n):
        if num <= 1:  # Numbers less than or equal to 1 are not prime, so skip them
            continue
        
        # Check for factors in the range from 2 to num-1
        for i in range(2, num):
            if (num % i) == 0:  # If num is divisible by i, it's not prime
                break
        else:
            ctr += 1  # If no factors are found, increment the counter (num is prime)

    return ctr  # Return the count of prime numbers

# Print the count of prime numbers up to 10 and 100
print(count_Primes_nums(10))
print(count_Primes_nums(100))

Sample Output:

4
25

Explanation:

Here is a breakdown of the above Python code:

  • First define a function named "count_Primes_nums()" that takes a limit 'n' as input.
  • Initialize a counter 'ctr' to store the number of prime numbers.
  • Use a for loop to iterate through numbers up to 'n'.
  • Check if the current number is less than or equal to 1; if so, skip it since numbers less than or equal to 1 are not prime.
  • Use another for loop to check for factors in the range from 2 to 'num-1'.
  • If a factor is found, break out of the loop; otherwise, increment the counter 'ctr'.
  • Return the final count of prime numbers.
  • Print the count of prime numbers up to 10 and 100 using the function.

Visual Presentation:

Python: Count the number of prime numbers less than a given non-negative number

Flowchart:

Flowchart: Python - Count the number of prime numbers less than a given non-negative number

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find and print the first 10 happy numbers.
Next: Write a Python program to check if two given strings are isomorphic to each other or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.