Reputation: 1
I reworked the program to get large prime numbers. Now it works fine, except I get a large number of red phrases at the end, after all the output is printed. Could someone please tell me why?
The end is of the output is:
(100000939.0, 'is prime')
(100000963.0, 'is prime')
(100000969.0, 'is prime')
The error is
Traceback (most recent call last):
File "C:/Users/Marcela/Documents/Prime numbers to 100", line 48, in <module>
loopfunction()
File "C:/Users/Marcela/Documents/Prime numbers to 100", line 35, in loopfunction
loopfunction()
File "C:/Users/Marcela/Documents/Prime numbers to 100", line 35, in loopfunction
loopfunction()
File "C:/Users/Marcela/Documents/Prime numbers to 100", line 35, in loopfunction
loopfunction()
...(many lines of it, the int ends with:)
File "C:/Users/Marcela/Documents/Prime numbers to 100", line 13, in loopfunction
while index <= 200000000.0:
RuntimeError: maximum recursion depth exceeded in cmp
Here is the script:
from __future__ import division
import sys
index=100000000.0
checker=2.0
def loopfunction():
global index
global checker
checker=2
while index <= 200000000.0:
if index>=200000001:
sys.exit(1)
while checker<=14473.0:
div = index/checker
roundiv=round(index/checker, 0)
if index == 1:
print (index, "is prime")
checker=2
index=index+1
loopfunction()
if checker == index:
print (index, "is prime")
checker=2
index=index+1
loopfunction()
if roundiv==div:
checker=2
index=index+1
loopfunction()
if checker==14473.0:
print (index, "is prime")
checker=2
index=index+1
loopfunction()
checker = checker +1
loopfunction()
Upvotes: 0
Views: 1722
Reputation: 104832
You can fix your recursion limit issue by simply not recursing. Your code already has the loops you need.
Just change the calls to loopfunction()
in the various if statements to break
.
While that is all that is needed to make the code function, I've noticed though that some of number of your if statements are unnecessary (either redundant with the loop conditions, or simply impossible to ever hit). You're also using while
loops where for _ in range()
loops would make more sense. Here's a greatly simplified version of your code, with some things renamed to clarify their purposes:
from math import sqrt
def primeFinder(start, end):
prime = True
for index in range(start, end):
for checker in range(2, int(sqrt(index))+1):
if index % checker == 0:
prime = False
break
if prime:
print("%d is prime" % index)
prime = True
primetest(100000000, 200000001)
This version will still take a very long time (probably hours). If you really want to test a hundred million values for primeness, you should probably investigate a better algorithm, such as the Sieve of Eratosthenes.
Upvotes: 2