我正在尝试在循环中使用break语句。我正在尝试构建一个函数,该函数可以找到小于用户 userInput
给定数字的最大素数。这是我的代码:
def primeFinder():
aVar = 2 # This is a possible factor
divisorList = [] # This is a factor list of userInout, the inputted number
while aVar <= userInput: # Checking until the variable cannot be a factor
if userInput % aVar == 0: # If userInput divided by the variable has a remainder of zero, it means it is a factor
divisorList.append(aVar) # Adding the factor to th factor list
aVar+=1 # Making the possible factor numeral one bigger to test again
else:
aVar +=1 # Making the possible factor numeral one bigger to test again
print divisorList
if len(divisorList) > 1: # If there are more than one factor...
print "Your input",userInput, " is not prime" # It is not prime
else:
print "Your input", userInput," is prime." # It is prime
当我找到最大素数时,我需要知道在哪里放置break语句来停止程序。我应该把它放在哪里以及为什么? 返回功能不起作用。发生的情况如下:
[2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500, 1000]
Your input 1000 is not prime
[3, 9, 27, 37, 111, 333, 999]
Your input 999 is not prime
[2, 499, 998]
Your input 998 is not prime
[997]
Your input 997 is prime.
[2, 3, 4, 6, 12, 83, 166, 249, 332, 498, 996]
Your input 996 is not prime
[5, 199, 995]
Your input 995 is not prime
[2, 7, 14, 71, 142, 497, 994]
Your input 994 is not prime
[3, 331, 993]
Your input 993 is not prime
[2, 4, 8, 16, 31, 32, 62, 124, 248, 496, 992]
Your input 992 is not prime
[991]
Your input 991 is prime.
[2, 3, 5, 6, 9, 10, 11, 15, 18, 22, 30, 33, 45, 55, 66, 90, 99, 110, 165, 198, 330, 495, 990]
Your input 990 is not prime
最佳答案
我认为你最好从上到下迭代以获得最大的质因数。像这样:
primeFactor=1
for aVar in range(userInput-1,1,-1): #loop from userInput-1 to 2
if userInput % aVar == 0:
primeFactor=aVar
break;
print "The largest prime factor is "+str(primeFactor).
关于python - 如何在这种特定情况下使用break子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36533072/