[英]Finding Prime Number and the count of the Prime number - Python
I a beginner at Python, still a tad confused about it. 我是Python的初学者,对此还是有点困惑。 I got to print out the prime numbers but now I am stuck trying to get the count of outputed prime numbers, please help.
我必须打印出质数,但是现在我一直想获取输出的质数,请帮忙。
import math
n= int (input("Enter an Integer: "))
for j in range(2, n+1):
if all(j%i!=0 for i in range(2,int(math.sqrt(j))+1)):
print (j)
count = 0
for j in range(2, n+1):
if j is True:
len(j)
print(str(len(j)))
I'll assume that your aim is to print all the prime numbers between 0 and n (Taken as input by the user) and count them. 我假设您的目标是打印0到n之间的所有质数(由用户输入)并计数。 All you have to do is declare 'count' before the first loop and increment it everytime a prime number is found.
您要做的就是在第一个循环之前声明“ count”,并在每次找到素数时将其递增。 The code will look something like this :
该代码将如下所示:
import math
n= int (input("Enter an Integer: "))
count = 0
for j in range(2, n+1):
if all(j%i!=0 for i in range(2,int(math.sqrt(j))+1)):
print (j)
count = count + 1
print (" Number of prime numbers is : " , count)
What is wrong in your code is that, in the second loop for j in range(2, n+1):
, j is an integer and if j is True:
is always false, as j is not a 'boolean' value. 您的代码的错误在于,在
for j in range(2, n+1):
中的j的第二个循环for j in range(2, n+1):
,j为整数, if j is True:
始终为false,因为j不是“布尔”值。 Hence print(str(len(j)))
is never executed. 因此,
print(str(len(j)))
永远不会执行。
All you have to do is add a counter in your code. 您要做的就是在代码中添加一个计数器。 Please go through the code below to see how that can be done.
请仔细阅读下面的代码,以了解如何实现。
import math
n= int (input("Enter an Integer: "))
count = 0
for j in range(2, n+1):
if all(j%i!=0 for i in range(2,int(math.sqrt(j))+1)):
print (j)
count = count + 1
print "Number of prime numbers between 1 and " + str(n) + " is " + str(count)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.