go - Calculating large exponentiation in Golang -
i've been trying calculating 2^100
in golang. understand limit of numeric type , tried using math/big
package. here's i've tried can't figure out why doesn't work.
i've used computation powers of two method calculate exponentiation.
package main import ( "fmt" "math/big" ) func main() { 2 := big.newint(2) hundred := big.newint(50) fmt.printf("2 ** 100 %d\n", expbypowoftwo(two, hundred)) } func expbypowoftwo(base, power *big.int) *big.int { result := big.newint(1) 0 := big.newint(0) power != 0 { if modby2(power) != 0 { multiply(result, base) } power = divideby2(power) base = multiply(base, base) } return result } func modby2(x *big.int) *big.int { return big.newint(0).mod(x, big.newint(2)) } func divideby2(x *big.int) *big.int { return big.newint(0).div(x, big.newint(2)) } func multiply(x, y *big.int) *big.int { return big.newint(0).mul(x, y) }
bigint package allows calculate x^y in log time (for reason called exp). need pass nil
last parameter.
package main import ( "fmt" "math/big" ) func main() { fmt.println(new(big.int).exp(big.newint(5), big.newint(20), nil)) }
if interested how calculate yourself, take @ implementation:
func powbig(a, n int) *big.int{ tmp := big.newint(int64(a)) res := big.newint(1) n > 0 { temp := new(big.int) if n % 2 == 1 { temp.mul(res, tmp) res = temp } temp = new(big.int) temp.mul(tmp, tmp) tmp = temp n /= 2 } return res }
or play on go playground.
Comments
Post a Comment