Golang實現(xiàn)Biginteger大數(shù)計算實例詳解
更新時間:2022年07月23日 15:48:34 作者:KunkkaWu
這篇文章主要為大家介紹了Golang實現(xiàn)Biginteger大數(shù)計算實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
正文
Golang中的big.Int庫支持大數(shù)計算,基于這個庫封裝了一層Bitinteger,支持字符串類型的大數(shù),加減乘除等計算。
其他計算可以參考基于big.Int來實現(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實現(xiàn)Biginteger大數(shù)計算實例詳解的詳細內容,更多關于Golang Biginteger大數(shù)計算的資料請關注腳本之家其它相關文章!
相關文章
手把手教你vscode配置golang開發(fā)環(huán)境的步驟
這篇文章主要介紹了手把手教你vscode配置golang開發(fā)環(huán)境的步驟,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03

