我是一名Python新手,所以如果答案显而易见并且我对一些简单的事情一无所知,我道歉。
我正在尝试计算素数因子的数量,以便打印出来:“它有X因素”,但我正在撞墙 - 我不确定如何或最好的方式计算先前生成的列表的数量。
我也对我的Prime Number决心的一部分感到困惑。它通常效果很好,但是当我输入15,25,35等数字时,它们都回来说,当它们不是时,数字是素数。它也不是5的倍数。
感谢所有帮助!
我的代码:
# Main Program
def main():
choice = "y"
while choice.lower() == "y":
print ("Prime Number Checker")
print ()
is_prime()
print()
choice = input("Try Again (y/n)?: ")
choice = "n"
while choice.lower() == "n":
break
# Prime number determination and Output
def is_prime():
num = int(input("Please enter an integer between 1 and 5,000: "))
if num > 1:
for i in range (2, num):
if (num % i) != 0:
print()
print ("The factors of your number are:")
factors (num)
print (num, "is a Prime Number")
break
elif (num % i) == 0:
print ()
print ("The factors of your number are:")
factors (num)
print (num, "is NOT a Prime Number")
numfacs (num)
break
else:
print ()
print ("Number not in range.")
print ()
# Factor Determination and Output
def factors(num):
for i in range (1, num+1):
if (num % i == 0):
print (i)
# Number of Facotors and Output
def numfacs(num):
for i in range (1, num+1):
if (num % i == 0):
list = []
print ("Length: ", len(list))
break
if __name__ == "__main__":
main()
答案 0 :(得分:0)
您的问题正在发生,因为如果您评估的数字(例如15)不能被for循环的第一个元素(在这种情况下为数字2)分割,那么它将被评估为素数。 要解决此问题,您可以在循环运行时添加标记(如果数字为素数)。如果它停止为素数(如果你可以将它除以另一个数字),则该标志变为False。
贝娄是我所说的一个有效例子。如果你不理解某些事情,请说出来。
# Main Program
def main():
choice = "y"
while choice.lower() == "y":
print ("Prime Number Checker")
print ()
is_prime()
print()
choice = input("Try Again (y/n)?: ")
choice = "n"
while choice.lower() == "n":
break
# Prime number determination and Output
def is_prime():
flag=False
num = int(input("Please enter an integer between 1 and 5,000: "))
if num > 1:
for i in range (2, num):
if (num % i) != 0:
flag=True
elif (num % i) == 0:
flag=False
print ()
print ("The factors of your number are:")
factors (num)
print (num, "is NOT a Prime Number")
numfacs (num)
break
if flag == True :
print(num,i,num % i)
print()
print ("The factors of your number are:")
factors (num)
print (num, "is a Prime Number")
else:
print ()
print ("Number not in range.")
print ()
# Factor Determination and Output
def factors(num):
for i in range (1, num+1):
if (num % i == 0):
print (i)
# Number of Facotors and Output
def numfacs(num):
for i in range (1, num+1):
if (num % i == 0):
list = []
print ("Length: ", len(list))
break
main()
注意:此行不适用于3.0版本的Python版本:
choice = input("Try Again (y/n)?: ")
而是使用它:
choice = str(raw_input("Try Again (y/n)?: "))