Project Euler Problem 686 Powers of Two - Solution


Powers of Two

   

Problem 686

27=128 is the first power of two whose leading digits are "12".
The next power of two whose leading digits are "12" is 280.
Define p(L,n) to be the nth-smallest value of j such that the base 10 representation of 2j begins with the digits of L.
So p(12,1)=7 and p(12,2)=80.
You are also given that p(123,45)=12710.
Find p(123,678910).

Test the first 3 digits of a large number is quite costly. 
So first thing first, think log().
---------------------
import math

lowerbound = math.log(1.23,10)
upperbound = math.log(1.24,10)

def testlog(i):
logi = math.log(2,10)*i
diff = (logi - int(logi))

return diff

We only care about the part after decimal point, thus diff = (logi - int(logi))
Test every "i" to see if the if falls in between lowerbound and upperbound. (diff>=lowerbound and diff<upperbound to be precise but does not really matter in this case.)

This alone should return correct answer in reasonable time.

Additional improvement that probably is not necessary:
diff = 0.99578959675025300 while i = 93 -> lower diff
diff = 0.00187915014031148 while i =196 -> increase diff
p(123,1)=90

full solution in python:
------------------

import math

maxn = 100000000
i= 90
rank = 0
previ=0
lowerbound = math.log(1.23,10)
upperbound = math.log(1.24,10)
def testdf(i):
    logi = math.log(2,10)*i
    diff = (logi - int(logi))    
    return diff

while(rank<678910):
    diff = testdf(i)    
    if (diff)>=upperbound:
        i+=93
    elif(diff < lowerbound):
        i+=196
    else:
        rank+=1
        previ=i
        i+=196
print(diff,rank,previ)


After thoughts:
This one is reasonably straight forward, IF you think of LOG(). 








Comments

Popular posts from this blog

Project Euler Problem 684 Inverse Digit Sum - Solution

Project Euler Problem 717 Summation of a Modular Formula - Solution