exp.go 569 B

12345678910111213141516171819202122232425262728
  1. package math
  2. import (
  3. "math/big"
  4. "github.com/ethereum/go-ethereum/common"
  5. )
  6. // wordSize is the size number of bits in a big.Int Word.
  7. const wordSize = 32 << (uint64(^big.Word(0))>>63)
  8. // Exp implement exponentiation by squaring algorithm.
  9. //
  10. // Courtesy @karalabe and @chfast
  11. func Exp(base, exponent *big.Int) *big.Int {
  12. result := big.NewInt(1)
  13. for _, word := range exponent.Bits() {
  14. for i := 0; i < wordSize; i++ {
  15. if word&1 == 1 {
  16. common.U256(result.Mul(result, base))
  17. }
  18. common.U256(base.Mul(base, base))
  19. word >>= 1
  20. }
  21. }
  22. return result
  23. }