Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,140 questions

56,014 answers

573 users

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

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

// return true if 2^n starts with prefix, else false
func startsWithPrefix(n int64, prefix int) bool {
    log2v := math.Log10(2.0)

    x := float64(n) * log2v
    frac := x - math.Floor(x)

    // count digits in prefix
    buf := fmt.Sprintf("%d", prefix)
    digits := len(buf)

    // compute leading digits
    leading := int(math.Floor(math.Pow(10, frac+float64(digits)-1)))

    return leading == prefix
}

func main() {
    prefix := 12

    for n := int64(1); ; n++ {
        if startsWithPrefix(n, prefix) {
            fmt.Println("First n =", n)
            fmt.Println("2 ^", n, "=", int(math.Pow(2, float64(n))))
            break
        }
    }
}



/*
run:

First n = 7
2 ^ 7 = 128

*/

 



answered Jun 13 by avibootz

Related questions

...