網站首頁 編程語言 正文
正文
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 }
原文鏈接:https://cloud.tencent.com/developer/article/2029133
相關推薦
- 2022-06-01 python畫立方體--魔方_python
- 2022-07-29 Docker容器的加載分層原理及commit鏡像_docker
- 2023-05-07 C語言中大小端問題實例探索解決方法_C 語言
- 2022-07-29 解決Vmware虛擬機安裝centos8報錯“Section?%Packages?Does?Not?
- 2022-07-23 C++超詳細講解稀疏矩陣_C 語言
- 2023-10-16 el-popover在原生table中,彈出多個以及內部取消按鈕無效問題
- 2022-08-22 詳解C#對Dictionary內容的通用操作_C#教程
- 2022-10-02 iOS簡單抽屜效果的實現方法_IOS
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支