# 如何在PYTHON中查找素数 [英] How to find prime numbers in python

### 问题描述

``````import math
def count_primes(num):
out = []

for i in range(3,num,2):
if all(i%j!=0 for j in range(3,int(math.sqrt(i))+1,2)):
out.append(i)

print(out)
``````

``````import math
def count_primes(num):
out = []
for i in range(3,num,2):
for j in range(3, int(math.sqrt(i))+1,2):
if i%j != 0:
out.append(i)
print(out)
``````

### 推荐答案

``````def collect_odd_primes(number):
primes = []

for candidate in range(3, number, 2):
for divisor in range(3, int(candidate ** 0.5) + 1, 2):
if candidate % divisor == 0:
break
else:  # no break
primes.append(candidate)

return primes

print(collect_odd_primes(40))
``````

``````> python3 test.py
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
>
``````

``````def count_odd_primes(number):
count = 0

for candidate in range(3, number, 2):
for divisor in range(3, int(candidate ** 0.5) + 1, 2):
if candidate % divisor == 0:
break
else:  # no break
count += 1

return count

print(count_odd_primes(40))
``````

``````> python3 test.py
11
>
``````