(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.


import std.math;
import std.stdio;
 
int p(int l, int n) {
    int test = 0;
    double logv = log(2.0) / log(10.0);
    int factor = 1;
    int loop = l;
    while (loop > 10) {
        factor *= 10;
        loop /= 10;
    }
    while (n > 0) {
        int val;
 
        test++;
        val = cast(int)(factor * pow(10.0, fmod(test * logv, 1)));
        if (val == l) {
            n--;
        }
    }
    return test;
}
 
void runTest(int l, int n) {
    writefln("p(%d, %d) = %d", l, n, p(l, n));
}
 
void main() {
    runTest(12, 1);
    runTest(12, 2);
    runTest(123, 45);
    runTest(123, 12345);
    runTest(123, 678910);
}