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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Multiplication.
package big
// Operands that are shorter than karatsubaThreshold are multiplied using
// "grade school" multiplication; for longer operands the Karatsuba algorithm
// is used.
var karatsubaThreshold = 40 // see calibrate_test.go
// mul sets z = x*y, using stk for temporary storage.
// The caller may pass stk == nil to request that mul obtain and release one itself.
func (z nat) mul(stk *stack, x, y nat) nat {
m := len(x)
n := len(y)
switch {
case m < n:
return z.mul(stk, y, x)
case m == 0 || n == 0:
return z[:0]
case n == 1:
return z.mulAddWW(x, y[0], 0)
}
// m >= n > 1
// determine if z can be reused
if alias(z, x) || alias(z, y) {
z = nil // z is an alias for x or y - cannot reuse
}
z = z.make(m + n)
// use basic multiplication if the numbers are small
if n < karatsubaThreshold {
basicMul(z, x, y)
return z.norm()
}
if stk == nil {
stk = getStack()
defer stk.free()
}
// Let x = x1:x0 where x0 is the same length as y.
// Compute z = x0*y and then add in x1*y in sections
// if needed.
karatsuba(stk, z[:2*n], x[:n], y)
if n < m {
clear(z[2*n:])
defer stk.restore(stk.save())
t := stk.nat(2 * n)
for i := n; i < m; i += n {
t = t.mul(stk, x[i:min(i+n, len(x))], y)
addTo(z[i:], t)
}
}
return z.norm()
}
// Operands that are shorter than basicSqrThreshold are squared using
// "grade school" multiplication; for operands longer than karatsubaSqrThreshold
// we use the Karatsuba algorithm optimized for x == y.
var basicSqrThreshold = 12 // see calibrate_test.go
var karatsubaSqrThreshold = 80 // see calibrate_test.go
// sqr sets z = x*x, using stk for temporary storage.
// The caller may pass stk == nil to request that sqr obtain and release one itself.
func (z nat) sqr(stk *stack, x nat) nat {
n := len(x)
switch {
case n == 0:
return z[:0]
case n == 1:
d := x[0]
z = z.make(2)
z[1], z[0] = mulWW(d, d)
return z.norm()
}
if alias(z, x) {
z = nil // z is an alias for x - cannot reuse
}
z = z.make(2 * n)
if n < basicSqrThreshold && n < karatsubaSqrThreshold {
basicMul(z, x, x)
return z.norm()
}
if stk == nil {
stk = getStack()
defer stk.free()
}
if n < karatsubaSqrThreshold {
basicSqr(stk, z, x)
return z.norm()
}
karatsubaSqr(stk, z, x)
return z.norm()
}
// basicSqr sets z = x*x and is asymptotically faster than basicMul
// by about a factor of 2, but slower for small arguments due to overhead.
// Requirements: len(x) > 0, len(z) == 2*len(x)
// The (non-normalized) result is placed in z.
func basicSqr(stk *stack, z, x nat) {
n := len(x)
if n < basicSqrThreshold {
basicMul(z, x, x)
return
}
defer stk.restore(stk.save())
t := stk.nat(2 * n)
clear(t)
z[1], z[0] = mulWW(x[0], x[0]) // the initial square
for i := 1; i < n; i++ {
d := x[i]
// z collects the squares x[i] * x[i]
z[2*i+1], z[2*i] = mulWW(d, d)
// t collects the products x[i] * x[j] where j < i
t[2*i] = addMulVVWW(t[i:2*i], t[i:2*i], x[0:i], d, 0)
}
t[2*n-1] = lshVU(t[1:2*n-1], t[1:2*n-1], 1) // double the j < i products
addVV(z, z, t) // combine the result
}
// mulAddWW returns z = x*y + r.
func (z nat) mulAddWW(x nat, y, r Word) nat {
m := len(x)
if m == 0 || y == 0 {
return z.setWord(r) // result is r
}
// m > 0
z = z.make(m + 1)
z[m] = mulAddVWW(z[0:m], x, y, r)
return z.norm()
}
// basicMul multiplies x and y and leaves the result in z.
// The (non-normalized) result is placed in z[0 : len(x) + len(y)].
func basicMul(z, x, y nat) {
clear(z[0 : len(x)+len(y)]) // initialize z
for i, d := range y {
if d != 0 {
z[len(x)+i] = addMulVVWW(z[i:i+len(x)], z[i:i+len(x)], x, d, 0)
}
}
}
// karatsuba multiplies x and y,
// writing the (non-normalized) result to z.
// x and y must have the same length n,
// and z must have length twice that.
func karatsuba(stk *stack, z, x, y nat) {
n := len(y)
if len(x) != n || len(z) != 2*n {
panic("bad karatsuba length")
}
// Fall back to basic algorithm if small enough.
if n < karatsubaThreshold || n < 2 {
basicMul(z, x, y)
return
}
// Let the notation x1:x0 denote the nat (x1<<N)+x0 for some N,
// and similarly z2:z1:z0 = (z2<<2N)+(z1<<N)+z0.
//
// (Note that z0, z1, z2 might be ≥ 2**N, in which case the high
// bits of, say, z0 are being added to the low bits of z1 in this notation.)
//
// Karatsuba multiplication is based on the observation that
//
// x1:x0 * y1:y0 = x1*y1:(x0*y1+y0*x1):x0*y0
// = x1*y1:((x0-x1)*(y1-y0)+x1*y1+x0*y0):x0*y0
//
// The second form uses only three half-width multiplications
// instead of the four that the straightforward first form does.
//
// We call the three pieces z0, z1, z2:
//
// z0 = x0*y0
// z2 = x1*y1
// z1 = (x0-x1)*(y1-y0) + z0 + z2
n2 := (n + 1) / 2
x0, x1 := &Int{abs: x[:n2].norm()}, &Int{abs: x[n2:].norm()}
y0, y1 := &Int{abs: y[:n2].norm()}, &Int{abs: y[n2:].norm()}
z0 := &Int{abs: z[0 : 2*n2]}
z2 := &Int{abs: z[2*n2:]}
// Allocate temporary storage for z1; repurpose z0 to hold tx and ty.
defer stk.restore(stk.save())
z1 := &Int{abs: stk.nat(2*n2 + 1)}
tx := &Int{abs: z[0:n2]}
ty := &Int{abs: z[n2 : 2*n2]}
tx.Sub(x0, x1)
ty.Sub(y1, y0)
z1.mul(stk, tx, ty)
clear(z)
z0.mul(stk, x0, y0)
z2.mul(stk, x1, y1)
z1.Add(z1, z0)
z1.Add(z1, z2)
addTo(z[n2:], z1.abs)
// Debug mode: double-check answer and print trace on failure.
const debug = false
if debug {
zz := make(nat, len(z))
basicMul(zz, x, y)
if z.cmp(zz) != 0 {
// All the temps were aliased to z and gone. Recompute.
z0 = new(Int)
z0.mul(stk, x0, y0)
tx = new(Int).Sub(x1, x0)
ty = new(Int).Sub(y0, y1)
z2 = new(Int)
z2.mul(stk, x1, y1)
print("karatsuba wrong\n")
trace("x ", &Int{abs: x})
trace("y ", &Int{abs: y})
trace("z ", &Int{abs: z})
trace("zz", &Int{abs: zz})
trace("x0", x0)
trace("x1", x1)
trace("y0", y0)
trace("y1", y1)
trace("tx", tx)
trace("ty", ty)
trace("z0", z0)
trace("z1", z1)
trace("z2", z2)
panic("karatsuba")
}
}
}
// karatsubaSqr squares x,
// writing the (non-normalized) result to z.
// z must have length 2*len(x).
// It is analogous to [karatsuba] but can run faster
// knowing both multiplicands are the same value.
func karatsubaSqr(stk *stack, z, x nat) {
n := len(x)
if len(z) != 2*n {
panic("bad karatsubaSqr length")
}
if n < karatsubaSqrThreshold || n < 2 {
basicSqr(stk, z, x)
return
}
// Recall that for karatsuba we want to compute:
//
// x1:x0 * y1:y0 = x1y1:(x0y1+y0x1):x0y0
// = x1y1:((x0-x1)*(y1-y0)+x1y1+x0y0):x0y0
// = z2:z1:z0
// where:
//
// z0 = x0y0
// z2 = x1y1
// z1 = (x0-x1)*(y1-y0) + z0 + z2
//
// When x = y, these simplify to:
//
// z0 = x0²
// z2 = x1²
// z1 = z0 + z2 - (x0-x1)²
n2 := (n + 1) / 2
x0, x1 := &Int{abs: x[:n2].norm()}, &Int{abs: x[n2:].norm()}
z0 := &Int{abs: z[0 : 2*n2]}
z2 := &Int{abs: z[2*n2:]}
// Allocate temporary storage for z1; repurpose z0 to hold tx.
defer stk.restore(stk.save())
z1 := &Int{abs: stk.nat(2*n2 + 1)}
tx := &Int{abs: z[0:n2]}
tx.Sub(x0, x1)
z1.abs = z1.abs.sqr(stk, tx.abs)
z1.neg = true
clear(z)
z0.abs = z0.abs.sqr(stk, x0.abs)
z2.abs = z2.abs.sqr(stk, x1.abs)
z1.Add(z1, z0)
z1.Add(z1, z2)
addTo(z[n2:], z1.abs)
// Debug mode: double-check answer and print trace on failure.
const debug = false
if debug {
zz := make(nat, len(z))
basicSqr(stk, zz, x)
if z.cmp(zz) != 0 {
// All the temps were aliased to z and gone. Recompute.
tx = new(Int).Sub(x0, x1)
z0 = new(Int).Mul(x0, x0)
z2 = new(Int).Mul(x1, x1)
z1 = new(Int).Mul(tx, tx)
z1.Neg(z1)
z1.Add(z1, z0)
z1.Add(z1, z2)
print("karatsubaSqr wrong\n")
trace("x ", &Int{abs: x})
trace("z ", &Int{abs: z})
trace("zz", &Int{abs: zz})
trace("x0", x0)
trace("x1", x1)
trace("z0", z0)
trace("z1", z1)
trace("z2", z2)
panic("karatsubaSqr")
}
}
}
// ifmt returns the debug formatting of the Int x: 0xHEX.
func ifmt(x *Int) string {
neg, s, t := "", x.Text(16), ""
if s == "" { // happens for denormalized zero
s = "0x0"
}
if s[0] == '-' {
neg, s = "-", s[1:]
}
// Add _ between words.
const D = _W / 4 // digits per chunk
for len(s) > D {
s, t = s[:len(s)-D], s[len(s)-D:]+"_"+t
}
return neg + s + t
}
// trace prints a single debug value.
func trace(name string, x *Int) {
print(name, "=", ifmt(x), "\n")
}
|