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

1 Answer

0 votes
using System;

class LeadingDigits
{
    // return true if 2^n starts with prefix, else false
    static bool StartsWithPrefix(long n, int prefix)
    {
        double log2v = Math.Log10(2.0);

        double x = n * log2v;
        double frac = x - Math.Floor(x);

        // count digits in prefix
        string buf = prefix.ToString();
        int digits = buf.Length;

        // compute leading digits
        int leading = (int)Math.Floor(Math.Pow(10, frac + digits - 1));

        return leading == prefix;
    }

    static void Main()
    {
        int prefix = 12;

        for (long n = 1; ; n++) {
            if (StartsWithPrefix(n, prefix)) {
                Console.WriteLine("First n = " + n);
                Console.WriteLine("2 ^ " + n + " = " + (int)Math.Pow(2, n));
                break;
            }
        }
    }
}


/*
run:

First n = 7
2 ^ 7 = 128

*/

 



answered 3 hours ago by avibootz

Related questions

...