Reputation: 21
When I run the following code:
number = input("Please Input Number...")
def prime_checker(divisor):
line = str(number) + " divided by " + str(divisor) + " = " + str(number/divisor)
if number == divisor:
print "This number is prime"
elif number % divisor == 0:
print line
else:
print "This number is not divisible by " + str(divisor)
next_number = divisor + 1
prime checker(next_number)
prime_checker(2)
I receive "RuntimeError: maximum recursion depth exceeded while getting the str of an object". I am trying to build a program which will check all the numbers under the inputted number to see if the inputted number is prime. If the number is divisible by anything, the program will give the division sentence. However, when the program checks to see if the inputted number is divisible by 999, the program starts doing the following:
Is there any way to fix this? Or is that the maximum value I can check?
Upvotes: 2
Views: 876
Reputation: 2036
There are many ways to search for prime numbers. I would suggest you google that if you are looking for something faster.
In answer to your problem, there isn't really a reason to be doing what you are doing recursively. If you are set on doing it with a "check every possible divisor" kind of method, iteratively will work just fine.
As mentioned in the comments, unless you change some internal options, Python won't let you recurse very deep. Looks like it stops around 1000 for you.
Try something like this for a simple iterative approach:
number = int(input("Please Input Number..."))
def is_prime(number):
# Check all numbers between 2 and the number you are concerned about
for divisor in range(2, number+1):
if number == divisor:
print('Number is prime')
return True
elif number % divisor == 0:
print(str(number) + " divided by " + str(divisor) + " = " + str(number/divisor))
return False
else:
print('Number is not divisible by ' + str(divisor))
is_prime(number)
Upvotes: 2