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

1 Answer

0 votes
// return true if 2^n starts with prefix, else false
function startsWithPrefix(n, prefix) {
    const log2v = Math.log10(2.0);

    const x = n * log2v;
    const frac = x - Math.floor(x);

    // count digits in prefix
    const buf = String(prefix);
    const digits = buf.length;

    // compute leading digits
    const leading = Math.floor(Math.pow(10, frac + digits - 1));

    return leading === prefix;
}

function main() {
    const prefix = 12;

    for (let n = 1; ; n++) {
        if (startsWithPrefix(n, prefix)) {
            console.log("First n = " + n);
            console.log("2 ^ " + n + " = " + Math.pow(2, n));
            break;
        }
    }
}

main();


/*
run:

First n = 7
2 ^ 7 = 128

*/

 



answered 1 hour ago by avibootz

Related questions

...