我很好奇是否有人可以修复我的代码,这是项目Euler问题3(600851475143的最大素数因素是什么?),到目前为止,我坚持一个能找到所有素数的程序100中的因素,但我得到一个除以0的错误信息,在我脑海中,代码似乎有效,但事实并非如此。除非绝对必要,否则我想保留while循环。感谢。
def isPrime(A):
x = 2
while x < A:
if A % x == 0:
return False
x += 1
return A
def isInt(x):
if x == int(x):
return True
return False
A = int(input("Number? "))
counter = 2
while counter <= A:
if isInt(A/isPrime(counter)) == True:
print(counter)
counter += 1
print ("Done")
答案 0 :(得分:0)
似乎关键问题是isPrime()
有时返回一个布尔值,其他时候返回输入(一个整数)。你应该避免让函数同时执行太多的事情 - 一个名为isPrime()
的函数应该只是指示输入是否为素数(即总是返回一个布尔值)。其他一些内联建议:
def isPrime(n): # n is a common variable name to use for "some number"
x = 2
while x < n:
if n % x == 0:
return False
x += 1 # this isn't an ideal way to detect primes, can you think of any improvements?
return True
def isInt(n): # use consistent variables - you used A above and x here, which is confusing
return n == int(n) # you can just return the boolean result directly
input = int(input("Number? ")) # use meaningful variable names when possible
counter = 2
while counter <= input:
# I *think* this is what you were trying to do:
# if counter is prime and input/counter is an integer.
# If not you may need to play with this conditional a bit
# also no need to say ' == True' here
if isPrime(counter) and isInt(input/counter):
print(counter)
counter += 1
print ("Done")
这应该运行(无论它是否有效,我留给你!),但它仍然没有那么高效。当您遇到更困难的Project Euler问题时,您需要开始关注效率和优化。我会让你深入研究这个问题,但这里有两个提示可以让你开始: