在Python中統(tǒng)計(jì)素?cái)?shù)的個數(shù)可以通過編寫一個函數(shù)來實(shí)現(xiàn),以下是一個示例代碼:
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def count_primes(n):
count = 0
for i in range(2, n):
if is_prime(i):
count += 1
return count
n = 100
print(f"There are {count_primes(n)} prime numbers less than {n}.")
在上面的代碼中,is_prime
函數(shù)用來判斷一個數(shù)是否為素?cái)?shù),count_primes
函數(shù)用來統(tǒng)計(jì)小于n的素?cái)?shù)的個數(shù)。通過調(diào)用count_primes
函數(shù)并傳入一個整數(shù)n,即可得到小于n的素?cái)?shù)的個數(shù)。