Reputation: 11
I am new to this and I really don't understand why this is happen. I am trying to run this program:
NumberToCheck=0
check=2
def checker():
global NumberToCheck
global check
check=2
while check < NumberToCheck:
if NumberToCheck % check == 0:
main()
check=check+1
else:
divider()
def main():
global NumberToCheck
while NumberToCheck < 600:
NumberToCheck=NumberToCheck+1
checker()
def divider():
if 600851475143 % NumberToCheck == 0:
print (NumberToCheck)
end()
main()
def end():
print ("end")
print ("start")
main()
And I keep getting this error:
start
1
71
Traceback (most recent call last):
File "/Users/marknorman/Documents/Problem 3.py", line 29, in <module>
main()
File "/Users/marknorman/Documents/Problem 3.py", line 21, in main
checker()
File "/Users/marknorman/Documents/Problem 3.py", line 15, in checker
divider()
File "/Users/marknorman/Documents/Problem 3.py", line 26, in divider
main()
And this would go forever in what looks like a random order unless I stop it.
Help?
Upvotes: 0
Views: 53
Reputation: 4341
Remove the main()
in divider. You're getting infinite recursion because instead of returning to main naturally you are calling the main()
method again which starts the process over again.
Also as a side note I would really suggest you stop using all these global variables. Return values from your functions instead
Here's a much simpler version that still uses a function. (For a problem like this you really don't even need functions anyway but it looks like you're trying to practice them)
def main():
numberToCheck = 600851475143
i = 2
#infinite loop
while 1:
if isDivisibleBy(numberToCheck, i):
# if our number is divisible print it out and stop the loop
print(numberToCheck, "is divisible by", i)
break
i += 1 #increment i
def isDivisibleBy(dividend, divisor):
if dividend % divisor == 0:
return True
return False
if __name__ == "__main__":
main()
Also note that the function isDivisibleBy could be shorted to just:
def isDivisibleBy(dividend, divisor):
return dividend % divisor == 0
But I figured that would be a little confusing for a beginner.
Upvotes: 2