I have an expression where I halve very large even integers, and I know the numerators are even so there is no fractional part, but I get an overflow error "OverflowError: integer division result too large for a float" because internally Python converts to floats.
return int(n/2) if (n%2) == 0 else int((3*n+1)/2)
I can fix this with mpmath via int(mpf(n)/2) if (n%2) == 0 else int(mpf(3*n+1)/2)
but it runs 3x slower than native division and I am looping millions of times so this is too long.
Is there an efficient way to halve a very large even integer?
Some have suggested integer division //
and I have tested it. The stats are: -
- Using
/
45 tests per sec - Using
//
5 tests per sec - Using
mpf
12 tests per sec - Using
>>
5 tests per sec
The integers I am working with are of the order 2**2000
but I want to consider larger ones so I need a method that works on unbounded integers.