Golang實(shí)現(xiàn)Biginteger大數(shù)計(jì)算實(shí)例詳解
正文
Golang中的big.Int庫支持大數(shù)計(jì)算,基于這個(gè)庫封裝了一層Bitinteger,支持字符串類型的大數(shù),加減乘除等計(jì)算。
其他計(jì)算可以參考基于big.Int來實(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 }
以上就是Golang實(shí)現(xiàn)Biginteger大數(shù)計(jì)算實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于Golang Biginteger大數(shù)計(jì)算的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
go語言實(shí)現(xiàn)mqtt協(xié)議的實(shí)踐
MQTT是一個(gè)基于客戶端-服務(wù)器的消息發(fā)布/訂閱傳輸協(xié)議。本文主要介紹了go語言實(shí)現(xiàn)mqtt協(xié)議的實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09如何使用Golang創(chuàng)建與讀取Excel文件
我最近工作忙于作圖,圖表,需要自己準(zhǔn)備數(shù)據(jù)源,所以經(jīng)常和Excel打交道,下面這篇文章主要給大家介紹了關(guān)于如何使用Golang創(chuàng)建與讀取Excel文件的相關(guān)資料,需要的朋友可以參考下2022-07-07