primes - Python 2.7.6(64-bit) overflow error in primality testing -


i running following code, version of erathosthene's sieve in python 2.7.6 64-bit on win8 on computer 4gb ram.

def erathosthenes_sieve2(n):     '''tests n>1 primality using improved erathostene's method'''       if n==2:           return true               if n%2==0:           return false               limit=long(math.floor(math.sqrt(n)))       in xrange(3,limit+1,2):          if n%i==0:              return false        return true   

when call function sufficiently big numbers, example 48112959837082048697(which prime) following error.

erathosthenes_sieve2(48112959837082048697)   --------------------------------------------------------------------------- overflowerror                             traceback (most recent call last) <ipython-input-28-b0a5b24a8b94> in <module>() ----> 1 erathosthenes_sieve2(48112959837082048697)  d:\repos\primalitytests\eratosthenes2.py in erathosthenes_sieve2(n)       9         return false      10     limit=long(math.floor(math.sqrt(n))) ---> 11     in xrange(3,limit+1,2):      12        if n%i==0:      13            return false  overflowerror: python int large convert c long 

what ways used work around problem? know not algorithm testing primes, part of project of comparing efficiency of different primality tests, please ignore that.

the issue xrange takes c long, meaning can't have arbitrary precision int. there way around this. to quote docs:

cpython implementation detail: xrange() intended simple , fast. implementations may impose restrictions achieve this. c implementation of python restricts arguments native c longs (“short” python integers), , requires number of elements fit in native c long. if larger range needed, alternate version can crafted using itertools module:

islice(count(start, step), (stop-start+step-1+2*(step<0))//step) 

so in case:

for in islice(count(3, 2), ((limit+1)-3+2-1+2*(2<0))//2):     ... 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -