-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbigint.go
127 lines (100 loc) · 1.86 KB
/
bigint.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package bigint
import (
"math/big"
"math/rand"
)
type mbi = *big.Int
func bi(n int) mbi {
return big.NewInt(int64(n))
}
func randBytes(n int) (res []byte) {
res = make([]byte, n)
for i := 0; i < n; i++ {
res[i] = byte(rand.Intn(1 << 8))
}
return
}
type Int struct {
i mbi
}
func FromInt(i int) Int {
return Int{bi(i)}
}
var (
Zero = FromInt(0)
One = FromInt(1)
Two = FromInt(2)
Three = FromInt(3)
Four = FromInt(4)
Five = FromInt(5)
Six = FromInt(6)
Seven = FromInt(7)
Eight = FromInt(8)
Nine = FromInt(9)
Ten = FromInt(10)
)
func FromBigInt(x *big.Int) Int {
return Int{bi(0).Set(x)}
}
func FromBytes(b []byte) Int {
return Int{bi(0).SetBytes(b)}
}
func FromString(s string, base int) (Int, bool) {
x, success := bi(0).SetString(s, base)
if !success {
return Int{}, false
}
return Int{x}, true
}
func Copy(x Int) Int {
return Int{bi(0).Set(x.i)}
}
func Exp(a Int, y Int, n Int) Int {
return Int{bi(0).Exp(a.i, y.i, n.i)}
}
func RandInt(n Int) Int {
x := randBytes(len(n.Bytes()))
return FromBytes(x).Mod(n)
}
func (b Int) Mul(x Int) Int {
return Int{bi(0).Mul(b.i, x.i)}
}
func (b Int) Mod(x Int) Int {
return Int{bi(0).Mod(b.i, x.i)}
}
func (b Int) Add(x Int) Int {
return Int{bi(0).Add(b.i, x.i)}
}
func (b Int) Sub(x Int) Int {
return Int{bi(0).Sub(b.i, x.i)}
}
func (b Int) Div(x Int) Int {
return Int{bi(0).Div(b.i, x.i)}
}
func (b Int) Equal(x Int) bool {
return b.Cmp(x) == 0
}
func (b Int) IsInt64() bool {
return b.i.IsInt64()
}
func (b Int) Int() int {
return int(b.i.Int64())
}
func (b Int) Cmp(x Int) int {
return b.i.Cmp(x.i)
}
func (b Int) Bytes() []byte {
return b.i.Bytes()
}
func (b Int) String() string {
return b.i.String()
}
func (b Int) BitLen() int {
return b.i.BitLen()
}
func (b Int) Text(base int) string {
return b.i.Text(base)
}
func (b Int) Sqrt() Int {
return Int{i: bi(0).Sqrt(b.i)}
}