How can I iterate over large numbers in Python using range ()?

I want to iterate over a large number, e.g. 600851475143, using the range () function in Python. But whenever I run the program, it gives me an OverflowError. I used the following code -

um = long(raw_input()) for j in range(1,num): .... 

I tried many times, but it does not work!

+4
source share
3 answers

Use itertools.islice() if your indexes are long numbers:

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

Python 3 range() can also handle long python.

Simplified your case:

 for j in islice(count(1), num - 1): 
+5
source

Although xrange seems to achieve what you want, it cannot handle large numbers. You may need to use this recipe from here.

CPython implementation details: xrange () is designed to be quick and easy. Implementations may impose constraints to achieve this. The C implementation of Python limits all arguments to the native C longs (short Python integers), and also requires that the number of elements matches the natural C long. If a larger range is required, an alternative version can be created using the itertools module: islice(count(start, step), (stop-start+step-1+2*(step<0))//step) .

+2
source

do not use, use

 counter = long(1) while counter < num: ... 
0
source

All Articles