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!
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.
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.
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.
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):
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With