Search code examples
pythonarbitrary-precision

Divide arbitrary binary integers by 3 in python


All the binary integers am given are always divisible by 3 so no floating-point values involved. The return value must also be a binary string Tried this but a and h are different yet they should be

>>> a="1111111111111111111111111111111111111111111111111111111111111111111111"
>>> f=int(a,base=2)
>>> print (f)
1180591620717411303423
>>> g = f/3
>>> c=int(g*3)
>>> print(c)
1180591620717411303424
>>> h = bin(c)
>>> print(h)
0b10000000000000000000000000000000000000000000000000000000000000000000000

Solution

  • Since your numbers are always divisible by 3 it is better to use // for integer division, because when you use floating point division for large numbers the result might not be exactly right.

    So your code will be something like:

    >>> a="1111111111111111111111111111111111111111111111111111111111111111111111"
    >>> f=int(a, base=2)
    >>> print(f)
    1180591620717411303423
    >>> g = f // 3
    >>> c = g * 3
    >>> print(c)
    1180591620717411303423
    >>> h = bin(c)
    >>> print(h)
    0b1111111111111111111111111111111111111111111111111111111111111111111111