Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating large exponentiation in Golang

I've been trying to calculating 2^100 in Golang. I understand the limit of numeric type and tried using math/big package. Here's what I've tried but I can't figure out why it doesn't work.

I've used computation by powers of two method to calculate the exponentiation.

package main

import (
    "fmt"
    "math/big"
)

func main() {
    two := big.NewInt(2)
    hundred := big.NewInt(50)
    fmt.Printf("2 ** 100    is %d\n", ExpByPowOfTwo(two, hundred))
}

func ExpByPowOfTwo(base, power *big.Int) *big.Int {
    result := big.NewInt(1)
    zero := big.NewInt(0)
    for power != zero {
        if modBy2(power) != zero {
            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)
}
like image 851
Ye Lin Aung Avatar asked May 12 '15 05:05

Ye Lin Aung


3 Answers

BigInt package allows you to calculate x^y in log time (for some reason it is called exp). All you need is to pass nil as a last parameter.

package main

import (
    "fmt"
    "math/big"
)

func main() {
    fmt.Println(new(big.Int).Exp(big.NewInt(5), big.NewInt(20), nil))
}

If you are interested how to calculate it by yourself, take a look at my implementation:

func powBig(a, n int) *big.Int{
    tmp := big.NewInt(int64(a))
    res := big.NewInt(1)
    for 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 with it on go playground.

like image 171
Salvador Dali Avatar answered Nov 04 '22 01:11

Salvador Dali


For example,

package main

import (
    "fmt"
    "math/big"
)

func main() {
    z := new(big.Int).Exp(big.NewInt(2), big.NewInt(100), nil)
    fmt.Println(z)
}

Output:

1267650600228229401496703205376

Since it's a power of two, you could also do a bit shift:

package main

import (
    "fmt"
    "math/big"
)

func main() {
    z := new(big.Int).Lsh(big.NewInt(1), 100)
    fmt.Println(z)
}

Output:

1267650600228229401496703205376
like image 37
peterSO Avatar answered Nov 04 '22 01:11

peterSO


You are returning immediately if power % 2 == 0. Instead, you just want to get the result of base ** (power /2). Then multiply result * result, and if power is even then multiply base to that.

like image 2
spalac24 Avatar answered Nov 04 '22 02:11

spalac24