- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Count Primes in Python

Suppose we have a limit n. We have to count the number of primes present in the range 2 to n. So if n = 10, the result will be 4. As there are four primes before 10, they are 2, 3, 5, 7.

To solve this, we will follow this approach −

- count = 0
- take one array prime = of size n + 1, and fill it with False
- for i = 0 to n, do
- if prime[i] = false, then
- increase count by 1
- set j = 2
- while j * i <n, then
- prime[i * j] = True
- j = j + 1

- if prime[i] = false, then
- return count

## Example

Let us see the following implementation to get a better understanding −

class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ count = 0 primes = [False for i in range(n+1)] for i in range(2,n): if primes[i] == False: count+=1 j = 2 while j*i<n: primes[j*i] = True j+=1 return count ob1 = Solution() print(ob1.countPrimes(50)) print(ob1.countPrimes(10))

## Input

n = 50 n = 10

## Output

15 4

- Related Articles
- Count Primes in Ranges in C++
- Count number of primes in an array in C++
- Count numbers < = N whose difference with the count of primes upto them is > = K in C++
- Count numbers which can be represented as sum of same parity primes in C++
- Check whether given three numbers are adjacent primes in Python
- Generate a list of Primes less than n in Python
- Find the sum of all Truncatable primes below N in Python
- Alternate Primes till N in C++?
- Print all multiplicative primes
- What are twin primes?
- Count and Say in Python
- Count Good Meals in Python
- Print all safe primes below N in C++
- Check if an integer can be expressed as a sum of two semi-primes in Python
- Program to check n can be represented as sum of k primes or not in Python

Advertisements