Given a positive integer n ≤ 10 7 , I need to find the least positive integer k such that the decimal representation of 2 k starts with the decimal representation of n .
So, for example, if n = 12, then k = 7 (because 2 7 = 12 8); if n = 134, then k = 27 (because 2 27 = 134 ,217,728); and if n = 82, then k = 209 (because 2 209 ≈ 8.2 3×10 62 ).
(If no such k exists, I need to return −1.)
I didn't even attempt to solve it with the formula (I have NO idea how), and decided to solve by calculating all powers of 2 up to 1000, putting them in a list, and then finding the index of the number that begins with n. The code works, but... It doesn't even pass the first test in the system. I have no clue why, because it works correctly for the above examples. Anyway, here is the code.
def find_all():
arr = []
n = 1
for i in range(1000):
arr.append(str(n))
n = n << 1
return arr
n = str(n)
NOT_FOUND = True
#n = input()
arr = find_all()
for i in arr:
if i.startswith(n):
print(arr.index(i), n)
NOT_FOUND = False
break
if NOT_FOUND:
print(-1, n)
What could be wrong?
Suppose you want to find a power of 2 that starts with 123.
This is equivalent to finding a multiple of log 10 (2) whose mantissa lies between 0.089905111439398 and 0.093421685162235 (because log 10 (123) = 2.089905111439398 and log 10 (124) = 2.093421685162235).
If you frame the question in this way, there's no need to calculate huge powers of 2. All you need is a bit of floating point arithmetic.
The following code works fairly well, but takes a good few seconds to produce answers when n is close to 10 7 :
def power_of_2_with_prefix(n):
# Find the minimum integer k such that the digits of 2^k
# start with the digits of n
from math import log10
#
# First deal with trivial cases
assert type(n) is int
if n == 1:
return 0
if n < 1:
return -1
#
# Calculate mantissa range
logmin = log10(n)
logmax = log10(n+1)
logmin -= int(logmin)
logmax -= int(logmax)
if logmax < logmin:
logmax += 1
#
# Now find a power of 2 whose log10 mantissa lies in this range
log2 = log10(2)
# Make sure k is large enough to include all trailing zeros of n
mink = log10(n) / log10(2)
x = 1
k = 0
while not (logmin <= x < logmax and k >= mink):
x += log2
if x >= 1:
x -= 1
k += 1
return k
assert power_of_2_with_prefix(0) == -1
assert power_of_2_with_prefix(1) == 0
assert power_of_2_with_prefix(2) == 1
assert power_of_2_with_prefix(4) == 2
assert power_of_2_with_prefix(40) == 12
assert power_of_2_with_prefix(28584) == 74715
assert power_of_2_with_prefix(28723) == 110057
assert power_of_2_with_prefix(9999999) == 38267831
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.