环球快看:Golang实现Biginteger大数计算实例详解
(资料图)
正文
Golang中的big.Int库支持大数计算,基于这个库封装了一层Bitinteger,支持字符串类型的大数,加减乘除等计算。
其他计算可以参考基于big.Int来实现。
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实现Biginteger大数计算实例详解的详细内容,更多关于Golang Biginteger大数计算的资料请关注脚本之家其它相关文章!
X 关闭
X 关闭
- 1转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 2充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 3好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 4名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?
- 5亚马逊云科技成立量子网络中心致力解决量子计算领域的挑战
- 6京东绿色建材线上平台上线 新增用户70%来自下沉市场
- 7网红淘品牌“七格格”chuu在北京又开一家店 潮人新宠chuu能红多久
- 8市场竞争加剧,有车企因经营不善出现破产、退网、退市
- 9北京市市场监管局为企业纾困减负保护经济韧性
- 10市场监管总局发布限制商品过度包装标准和第1号修改单

