Range is too large Python

前端 未结 6 1401
逝去的感伤
逝去的感伤 2020-12-08 21:39

I\'m trying to find the largest prime factor of the number x, Python gives me the error that the range is too large. I\'ve tried using x range but I get an OverflowError: Py

6条回答
  •  萌比男神i
    2020-12-08 22:36

    In old (2.x) versions of Python, xrange can only handle Python 2.x ints, which are bound by the native long integer size of your platform. Additionally, range allocates a list with all numbers beforehand on Python 2.x, and is therefore unsuitable for large arguments.

    You can either switch to 3.x (recommended), or a platform where long int (in C) is 64 bit long, or use the following drop-in:

    import itertools
    range = lambda stop: iter(itertools.count().next, stop)
    

    Equivalently, in a plain form:

    def range(stop):
       i = 0
       while i < stop:
           yield i
           i += 1
    

提交回复
热议问题