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

Soham Banerjee picture Soham Banerjee · Mar 31, 2013 · Viewed 10.1k times · Source

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

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

I have tried it many times but it is not working!

Answer

Martijn Pieters picture Martijn Pieters · Mar 31, 2013

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

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

Python 3's range() can handle python longs as well.

Simplified to your case:

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