前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang实现Biginteger大数计算

Golang实现Biginteger大数计算

原创
作者头像
KunkkaWu
修改2022-06-24 11:21:54
1.6K0
修改2022-06-24 11:21:54
举报
文章被收录于专栏:算法协议算法协议

Golang中的big.Int库支持大数计算,基于这个库封装了一层Bitinteger,支持字符串类型的大数,加减乘除等计算。 其他计算可以参考基于big.Int来实现。

代码语言:txt
复制
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

}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档