python – How to halve a very large even integer without getting an float overflow error?

Both of these options seem pretty fast:

In [387]: n = int("12" * 10_000)

In [388]: %timeit n//2
20.6 µs ± 593 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [389]: %timeit n>>1
3.81 µs ± 37.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

You can use wombo_combo = lambda x : x>>1 if x%2 == 0 else (3*x + 1)>>1

Edit:

I think if you’re looking to speed things up you can also do something like this, which is slightly faster than %

if n & 1 == 0: # even
    return n >> 1
# odd
return (n*3 + 1) >> 1

Here are more timings for you:

In [78]: n = 2**2000

In [79]: %timeit n>>1 if n&1==0 else (n*3+1)>>1
288 ns ± 8.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [80]: %timeit n//2 if n&1==0 else (n*3+1)//2
566 ns ± 5.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [81]: %timeit n//2 if n%2==0 else (n*3+1)//2
965 ns ± 3.24 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Also if you know the numerator is always positive you should just avoid doing the conditional check. That’s extra wasted time that could be spent shifting them bits!

Read more here: Source link