[英]Find number of prime numbers between 2 and n
I am trying to find the number of prime numbers between 2 and n, where n is provided by the user. 我试图找到2到n之间的质数,其中n由用户提供。 I can't seem to make it work.
我似乎无法使其工作。 here's my code:
这是我的代码:
>>> def numOfPrime(n):
count = 0
for i in range(2,n):
p = True
for j in range(2,i):
if i % j ==0:
p = False
if p == True:
count += 1
return count
>>> numOfPrime(100)
0
The indentation of your if
block is incorrect. if
块的缩进不正确。 It should be in the loop. 它应该在循环中。
def numOfPrime(n):
count = 0
for i in range(2,n):
p = True
for j in range(2,i):
if i % j ==0:
p = False
if p == True:
count += 1
return count
Now numOfPrime(100)
returns 25, which correctly accounts for 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, and 97. 现在
numOfPrime(100)
返回25,它正确地numOfPrime(100)
, 71、73、79、83、89和97。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.