python - Segmentation fault in Prime Number generator -
i aware following isn't fastest way of generating list of primes posed myself problem , before googling wrote following program. works fine numbers < ~ 44,000 gives segmentation fault when ran on 2ghz core 2 duo macbook. not interested in alternative methods @ moment in why giving me seg fault.
the last prime able calculate 42751 before dies saying 'segmentation fault'.
from sys import argv, exit, setrecursionlimit def isprime(no, halfno, x = 3): # if counted through , numbers 3 x not factors prime if x > halfno: print no return 1 # x factor? if no % x == 0: return 0 else: isprime(no, halfno, x + 2) path, limlow, limhigh = argv limlow = int(limlow) limhigh = int(limhigh) setrecursionlimit(limhigh) # negitive numbers, 0 , 1 not primes answer invalid if limlow < 2: exit('invalid input'); # if lower limit not prime increase 1 if limlow % 2 == 0: limlow += 1 while (limlow <= limhigh): isprime(limlow, limlow / 2) limlow += 2
you might getting stack overflow many recusive calls on stack. @ 42751 have 21375 depth function call stack. in such case, refining method might needed.
a handy little routine check primeness can written (pseudocode):
if n < 2 return false; if n == 2 or n == 3 return true; if n % 2 == 0 return false; if n % 3 == 0 return false; (i = 6; < sqrt(n); += 6) { if (n % (i - 1) == 0) return false; if (n % (i + 1) == 0) return false; } return true;
this method works because of following:
- if n less 2, can't prime
- if n 2 or 3 must prime
- if n not 2 or 3 divisible either, not prime
- all prime numbers aside 2 , 3 can written in form 6k+1 or 6k-1. if number prime, not evenly divisible other prime number. need check until square root of n because more not divide evenly n.
Comments
Post a Comment