日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Golang實(shí)現(xiàn)Biginteger大數(shù)計(jì)算實(shí)例詳解_Golang

作者:KunkkaWu ? 更新時(shí)間: 2022-09-16 編程語(yǔ)言

正文

Golang中的big.Int庫(kù)支持大數(shù)計(jì)算,基于這個(gè)庫(kù)封裝了一層Bitinteger,支持字符串類型的大數(shù),加減乘除等計(jì)算。

其他計(jì)算可以參考基于big.Int來(lái)實(shí)現(xiàn)。

package BigIntege
import (
    "fmt"
    "math/big"
)
const DecBase = 10
// BigInteger wrapper for big.Int
type BigInteger struct {
    Value *big.Int
}
func NewBigInteger(value string) \*BigInteger {
    var val big.Int
    newVal, ok := val.SetString(value, DecBase)
    if ok {
        return &BigInteger{
            Value: newVal,
        }
    }
    return NewZeroBigInteger()
}
func NewZeroBigInteger() *BigInteger {
    return &BigInteger{
        Value: big.NewInt(0),
    }
}
func (x *BigInteger) Add(y *BigInteger) {
    x.Value = x.Value.Add(x.Value, y.Value)
}
func (x *BigInteger) Sub(y *BigInteger) {
    x.Value = x.Value.Sub(x.Value, y.Value)
}
// Cmp compares x and y and returns:
//
//   -1 if x <  y
//    0 if x == y
//   +1 if x >  y
func (x *BigInteger) Cmp(y *BigInteger) int {
    return x.Value.Cmp(y.Value)
}
func (x *BigInteger) String() string {
    return x.Value.String()
}
// Sum 加法
func Sum(x, y *BigInteger) *BigInteger {
    z := NewZeroBigInteger()
    z.Add(x)
    z.Add(y)
    return z
}
// Sub 減法
func Sub(x, y *BigInteger) *BigInteger {
    z := NewBigInteger(x.String())
    z.Sub(y)
    return z
}
// Mul 懲罰
func Mul(x, y \*BigInteger) \*BigInteger {
    t := NewZeroBigInteger()
    z := t.Value.Mul(x.Value, y.Value)
    return &BigInteger{Value: z}
}
// Div 除法
func Div(x, y *BigInteger) *BigInteger {
    t := NewZeroBigInteger()
    z := t.Value.Div(x.Value, y.Value)
    return &BigInteger{Value: z}
}
func isValidBigInt(val string) error {
    _, ok := big.NewInt(0).SetString(val, 10)
    if !ok {
        return fmt.Errorf("parse string to big.Int failed, actual: %s", val)
    }
    return nil
}

原文鏈接:https://cloud.tencent.com/developer/article/2029133

欄目分類
最近更新