w3resource

Python: Print the number of prime numbers which are less than or equal to a given integer

Python Basic - 1: Exercise-38 with Solution

Write a Python program to print the number of prime numbers that are less than or equal to a given number.

Input:
n (1 ≤ n ≤ 999,999)
Input the number(n): 35
Number of prime numbers which are less than or equal to n.: 11

Sample Solution:

Python Code:

# Initialize a list to represent prime numbers up to 500000
primes = [1] * 500000
primes[0] = 0  # 0 is not a prime number

# Sieve of Eratosthenes: Mark non-prime numbers in the list
for i in range(3, 1000, 2):
    if primes[i // 2]:
        primes[(i * i) // 2::i] = [0] * len(primes[(i * i) // 2::i])

# Prompt user to input a number 'n'
print("Input the number(n):")
n = int(input())

# Check and print the number of primes less than or equal to 'n'
if n < 4:
    print("Number of prime numbers which are less than or equal to n.:", n - 1)
else:
    print("Number of prime numbers which are less than or equal to n.:", sum(primes[:(n + 1) // 2]) + 1)

Sample Output:

Input the number(n):
 35
Number of prime numbers which are less than or equal to n.: 11

Explanation:

Here is a breakdown of the above Python code:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/basic/python-basic-1-exercise-38.php