Python tips: calculate the number of prime numbers

Count the number of prime numbers less than N

A prime number (prime number) is also called a prime number, which is a natural number greater than 1 and has no other factors except 1 and itself. The opposite is a composite number, and there are infinite prime numbers.

Count the number of prime numbers less than N

  • 输入: 10
  • 输出: 4

There are 4 prime numbers less than 10: 2, 3, 5, 7

Method 1: Direct Judgment

from math import sqrt
def isPrime(n):
    for i in range(2,int(sqrt(n))+1):
        if n%i==0:
            return False
    return True

def countPrime(N):
    if N<3:
        return 0
    else:
        cou = 1
        for i in range(3,N,2):
            if isPrime(i):
                cou += 1
    return cou
print(countPrime(2))
print(countPrime(5))
print(countPrime(100))
print(countPrime(100000))  
print(countPrime(10000000))#在n>100000000时达到计算瓶颈

Output:
0
2
25
9592
664579

Method 2: Elsieve sieve method

The Sieve of Eratosthenes, referred to as the Sieve of Eratosthenes, is a screening method proposed by the ancient Greek mathematician Eratosthenes (Eratosthenes 274BC.~194BC.).

To get all the prime numbers within the natural number n, the multiples of all prime numbers not greater than n must be removed, and the rest are prime numbers. The specific steps are as follows: first use 2 to sieve, that is, keep 2, and remove the multiples of 2; Then use the next prime number, that is, 3 to sieve, keep 3, and remove multiples of 3; then use the next prime number 5 to sieve, keep 5, and remove multiples of 5; repeat.

insert image description here

def couPrime(N):
    primeList = [True]*N
    for i in range(2,N):
        if(primeList[i]):
            for j in range(2*i,N,i):
                primeList[j]=False
    cou = primeList.count(True)-2
    return cou
print(couPrime(100000000)) #在n>1000000000达到计算瓶颈

Output:
5761455

Guess you like

Origin blog.csdn.net/apr15/article/details/128961329