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 2 hours ago by avibootz

Related questions

...