Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 285
Soham Banerjee Avatar asked Mar 31 '13 01:03

Soham Banerjee


People also ask

What is the correct way to iterate over a range of numbers in Python?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Can a for loop iterate over a range of numbers?

For loop is used to iterate the elements over the given range. We can use for loop to append, print, or perform some operation on the given range of integers.

How do you iterate through a range in a list?

We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list. The output would be the same as above.


2 Answers

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):
like image 85
Martijn Pieters Avatar answered Nov 15 '22 00:11

Martijn Pieters


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

CPython implementation detail: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (“short” Python integers), and also requires that the number of elements fit in a native C long. If a larger range is needed, an alternate version can be crafted using the itertools module: islice(count(start, step), (stop-start+step-1+2*(step<0))//step).

like image 24
jamylak Avatar answered Nov 15 '22 01:11

jamylak