How to find the first power of 2 whose leading digits are 12 in Python

1 Answer

0 votes
import math

# return true if 2^n starts with prefix, else false
def startsWithPrefix(n, prefix):
    log2v = math.log10(2.0)

    x = n * log2v
    frac = x - math.floor(x)

    # count digits in prefix
    buf = str(prefix)
    digits = len(buf)

    # compute leading digits
    leading = int(math.floor(math.pow(10, frac + digits - 1)))

    return leading == prefix


def main():
    prefix = 12

    n = 1
    while True:
        if startsWithPrefix(n, prefix):
            print("First n =", n)
            print("2 ^", n, "=", int(math.pow(2, n)))
            break
        n += 1


main()


"""
run:

First n = 7
2 ^ 7 = 128

"""

 



answered 2 hours ago by avibootz

Related questions

...