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

1 Answer

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

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

    // count digits in prefix
    const buf: string = prefix.toString();
    const digits: number = buf.length;

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

    return leading === prefix;
}

function main(): void {
    const prefix: number = 12;

    for (let n: number = 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 3 hours ago by avibootz

Related questions

...