(This task is taken from a   Project Euler   problem.)

(All numbers herein are expressed in base ten.)


27   =   128   and   7   is
the first power of   2   whose leading decimal digits are   12.

The next power of   2   whose leading decimal digits
are   12   is   80,

280   =   1208925819614629174706176.



Define        p(L,n)      to be the  nth-smallest
value of    j    such that the base ten 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



Task

   find: 
     p(12, 1)  
     p(12, 2)  
     p(123, 45)  
     p(123, 12345)  
     p(123, 678910)  
   display the results here, on this page.


with javascript_semantics
function p(integer L, n)
    atom logof2 = log10(2)
    integer places = trunc(log10(L)),
            nfound = 0, i = 1
    while true do
        atom a = i * logof2,
             b = trunc(power(10,a-trunc(a)+places))
        if L == b then
            nfound += 1
            if nfound == n then exit end if
        end if
        i += 1
    end while
    return i
end function
 
constant tests = {{12, 1}, {12, 2}, {123, 45}, {123, 12345}, {123, 678910}}
include ordinal.e
include mpfr.e
mpz z = mpz_init()
atom t0 = time()
for i=1 to length(tests)-(2*(platform()=JS)) do
    integer {L,n} = tests[i], pln = p(L,n)
    mpz_ui_pow_ui(z,2,pln)
    integer digits = mpz_sizeinbase(z,10)
    string st = iff(digits>2e6?sprintf("%,d digits",digits):
                               shorten(mpz_get_str(z),"digits",5)) 
    printf(1,"The %d%s power of 2 that starts with %d is %d [i.e. %s]\n",{n,ord(n),L,pln,st})
end for
?elapsed(time()-t0)
