about summary refs log tree commit diff
path: root/vendor/modernc.org/mathutil/mathutil.go
blob: 6db6640936bd593be7fc08c39e9fabb3427a0ee2 (plain)
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
// Copyright (c) 2014 The mathutil Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package mathutil provides utilities supplementing the standard 'math' and
// 'math/rand' packages.
//
// Release history and compatibility issues
//
// 2020-12-20 v1.2.1 fixes MulOverflowInt64.
//
// 2020-12-19 Added {Add,Sub,Mul}OverflowInt{8,16,32,64}
//
// 2018-10-21 Added BinaryLog
//
// 2018-04-25: New functions for determining Max/Min of nullable values. Ex:
//  func MaxPtr(a, b *int) *int {
//  func MinPtr(a, b *int) *int {
//  func MaxBytePtr(a, b *byte) *byte {
//  func MinBytePtr(a, b *byte) *byte {
//  ...
//
// 2017-10-14: New variadic functions for Max/Min. Ex:
//  func MaxVal(val int, vals ...int) int {
//  func MinVal(val int, vals ...int) int {
//  func MaxByteVal(val byte, vals ...byte) byte {
//  func MinByteVal(val byte, vals ...byte) byte {
//  ...
//
// 2016-10-10: New functions QuadPolyDiscriminant and QuadPolyFactors.
//
// 2013-12-13: The following functions have been REMOVED
//
// 	func Uint64ToBigInt(n uint64) *big.Int
// 	func Uint64FromBigInt(n *big.Int) (uint64, bool)
//
// 2013-05-13: The following functions are now DEPRECATED
//
// 	func Uint64ToBigInt(n uint64) *big.Int
// 	func Uint64FromBigInt(n *big.Int) (uint64, bool)
//
// These functions will be REMOVED with Go release 1.1+1.
//
// 2013-01-21: The following functions have been REMOVED
//
// 	func MaxInt() int
// 	func MinInt() int
// 	func MaxUint() uint
// 	func UintPtrBits() int
//
// They are now replaced by untyped constants
//
// 	MaxInt
// 	MinInt
// 	MaxUint
// 	UintPtrBits
//
// Additionally one more untyped constant was added
//
// 	IntBits
//
// This change breaks any existing code depending on the above removed
// functions.  They should have not been published in the first place, that was
// unfortunate. Instead, defining such architecture and/or implementation
// specific integer limits and bit widths as untyped constants improves
// performance and allows for static dead code elimination if it depends on
// these values. Thanks to minux for pointing it out in the mail list
// (https://groups.google.com/d/msg/golang-nuts/tlPpLW6aJw8/NT3mpToH-a4J).
//
// 2012-12-12: The following functions will be DEPRECATED with Go release
// 1.0.3+1 and REMOVED with Go release 1.0.3+2, b/c of
// http://code.google.com/p/go/source/detail?r=954a79ee3ea8
//
// 	func Uint64ToBigInt(n uint64) *big.Int
// 	func Uint64FromBigInt(n *big.Int) (uint64, bool)
package mathutil // import "modernc.org/mathutil"

import (
	"math"
	"math/big"
)

// Architecture and/or implementation specific integer limits and bit widths.
const (
	MaxInt      = 1<<(IntBits-1) - 1
	MinInt      = -MaxInt - 1
	MaxUint     = 1<<IntBits - 1
	IntBits     = 1 << (^uint(0)>>32&1 + ^uint(0)>>16&1 + ^uint(0)>>8&1 + 3)
	UintPtrBits = 1 << (^uintptr(0)>>32&1 + ^uintptr(0)>>16&1 + ^uintptr(0)>>8&1 + 3)
)

var (
	_1 = big.NewInt(1)
	_2 = big.NewInt(2)
)

// GCDByte returns the greatest common divisor of a and b. Based on:
// http://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations
func GCDByte(a, b byte) byte {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

// GCDUint16 returns the greatest common divisor of a and b.
func GCDUint16(a, b uint16) uint16 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

// GCDUint32 returns the greatest common divisor of a and b.
func GCDUint32(a, b uint32) uint32 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

// GCDUint64 returns the greatest common divisor of a and b.
func GCDUint64(a, b uint64) uint64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

// ISqrt returns floor(sqrt(n)). Typical run time is few hundreds of ns.
func ISqrt(n uint32) (x uint32) {
	if n == 0 {
		return
	}

	if n >= math.MaxUint16*math.MaxUint16 {
		return math.MaxUint16
	}

	var px, nx uint32
	for x = n; ; px, x = x, nx {
		nx = (x + n/x) / 2
		if nx == x || nx == px {
			break
		}
	}
	return
}

// SqrtUint64 returns floor(sqrt(n)). Typical run time is about 0.5 µs.
func SqrtUint64(n uint64) (x uint64) {
	if n == 0 {
		return
	}

	if n >= math.MaxUint32*math.MaxUint32 {
		return math.MaxUint32
	}

	var px, nx uint64
	for x = n; ; px, x = x, nx {
		nx = (x + n/x) / 2
		if nx == x || nx == px {
			break
		}
	}
	return
}

// SqrtBig returns floor(sqrt(n)). It panics on n < 0.
func SqrtBig(n *big.Int) (x *big.Int) {
	switch n.Sign() {
	case -1:
		panic(-1)
	case 0:
		return big.NewInt(0)
	}

	var px, nx big.Int
	x = big.NewInt(0)
	x.SetBit(x, n.BitLen()/2+1, 1)
	for {
		nx.Rsh(nx.Add(x, nx.Div(n, x)), 1)
		if nx.Cmp(x) == 0 || nx.Cmp(&px) == 0 {
			break
		}
		px.Set(x)
		x.Set(&nx)
	}
	return
}

// Log2Byte returns log base 2 of n. It's the same as index of the highest
// bit set in n.  For n == 0 -1 is returned.
func Log2Byte(n byte) int {
	return log2[n]
}

// Log2Uint16 returns log base 2 of n. It's the same as index of the highest
// bit set in n.  For n == 0 -1 is returned.
func Log2Uint16(n uint16) int {
	if b := n >> 8; b != 0 {
		return log2[b] + 8
	}

	return log2[n]
}

// Log2Uint32 returns log base 2 of n. It's the same as index of the highest
// bit set in n.  For n == 0 -1 is returned.
func Log2Uint32(n uint32) int {
	if b := n >> 24; b != 0 {
		return log2[b] + 24
	}

	if b := n >> 16; b != 0 {
		return log2[b] + 16
	}

	if b := n >> 8; b != 0 {
		return log2[b] + 8
	}

	return log2[n]
}

// Log2Uint64 returns log base 2 of n. It's the same as index of the highest
// bit set in n.  For n == 0 -1 is returned.
func Log2Uint64(n uint64) int {
	if b := n >> 56; b != 0 {
		return log2[b] + 56
	}

	if b := n >> 48; b != 0 {
		return log2[b] + 48
	}

	if b := n >> 40; b != 0 {
		return log2[b] + 40
	}

	if b := n >> 32; b != 0 {
		return log2[b] + 32
	}

	if b := n >> 24; b != 0 {
		return log2[b] + 24
	}

	if b := n >> 16; b != 0 {
		return log2[b] + 16
	}

	if b := n >> 8; b != 0 {
		return log2[b] + 8
	}

	return log2[n]
}

// ModPowByte computes (b^e)%m. It panics for m == 0 || b == e == 0.
//
// See also: http://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method
func ModPowByte(b, e, m byte) byte {
	if b == 0 && e == 0 {
		panic(0)
	}

	if m == 1 {
		return 0
	}

	r := uint16(1)
	for b, m := uint16(b), uint16(m); e > 0; b, e = b*b%m, e>>1 {
		if e&1 == 1 {
			r = r * b % m
		}
	}
	return byte(r)
}

// ModPowUint16 computes (b^e)%m. It panics for m == 0 || b == e == 0.
func ModPowUint16(b, e, m uint16) uint16 {
	if b == 0 && e == 0 {
		panic(0)
	}

	if m == 1 {
		return 0
	}

	r := uint32(1)
	for b, m := uint32(b), uint32(m); e > 0; b, e = b*b%m, e>>1 {
		if e&1 == 1 {
			r = r * b % m
		}
	}
	return uint16(r)
}

// ModPowUint32 computes (b^e)%m. It panics for m == 0 || b == e == 0.
func ModPowUint32(b, e, m uint32) uint32 {
	if b == 0 && e == 0 {
		panic(0)
	}

	if m == 1 {
		return 0
	}

	r := uint64(1)
	for b, m := uint64(b), uint64(m); e > 0; b, e = b*b%m, e>>1 {
		if e&1 == 1 {
			r = r * b % m
		}
	}
	return uint32(r)
}

// ModPowUint64 computes (b^e)%m. It panics for m == 0 || b == e == 0.
func ModPowUint64(b, e, m uint64) (r uint64) {
	if b == 0 && e == 0 {
		panic(0)
	}

	if m == 1 {
		return 0
	}

	return modPowBigInt(big.NewInt(0).SetUint64(b), big.NewInt(0).SetUint64(e), big.NewInt(0).SetUint64(m)).Uint64()
}

func modPowBigInt(b, e, m *big.Int) (r *big.Int) {
	r = big.NewInt(1)
	for i, n := 0, e.BitLen(); i < n; i++ {
		if e.Bit(i) != 0 {
			r.Mod(r.Mul(r, b), m)
		}
		b.Mod(b.Mul(b, b), m)
	}
	return
}

// ModPowBigInt computes (b^e)%m. Returns nil for e < 0. It panics for m == 0 || b == e == 0.
func ModPowBigInt(b, e, m *big.Int) (r *big.Int) {
	if b.Sign() == 0 && e.Sign() == 0 {
		panic(0)
	}

	if m.Cmp(_1) == 0 {
		return big.NewInt(0)
	}

	if e.Sign() < 0 {
		return
	}

	return modPowBigInt(big.NewInt(0).Set(b), big.NewInt(0).Set(e), m)
}

var uint64ToBigIntDelta big.Int

func init() {
	uint64ToBigIntDelta.SetBit(&uint64ToBigIntDelta, 63, 1)
}

var uintptrBits int

func init() {
	x := uint64(math.MaxUint64)
	uintptrBits = BitLenUintptr(uintptr(x))
}

// UintptrBits returns the bit width of an uintptr at the executing machine.
func UintptrBits() int {
	return uintptrBits
}

// AddUint128_64 returns the uint128 sum of uint64 a and b.
func AddUint128_64(a, b uint64) (hi uint64, lo uint64) {
	lo = a + b
	if lo < a {
		hi = 1
	}
	return hi, lo
}

// MulUint128_64 returns the uint128 bit product of uint64 a and b.
func MulUint128_64(a, b uint64) (hi, lo uint64) {
	/*
		2^(2 W) ahi bhi + 2^W alo bhi + 2^W ahi blo + alo blo

		FEDCBA98 76543210 FEDCBA98 76543210
		                  ---- alo*blo ----
		         ---- alo*bhi ----
		         ---- ahi*blo ----
		---- ahi*bhi ----
	*/
	const w = 32
	const m = 1<<w - 1
	ahi, bhi, alo, blo := a>>w, b>>w, a&m, b&m
	lo = alo * blo
	mid1 := alo * bhi
	mid2 := ahi * blo
	c1, lo := AddUint128_64(lo, mid1<<w)
	c2, lo := AddUint128_64(lo, mid2<<w)
	_, hi = AddUint128_64(ahi*bhi, mid1>>w+mid2>>w+c1+c2)
	return
}

// PowerizeBigInt returns (e, p) such that e is the smallest number for which p
// == b^e is greater or equal n. For n < 0 or b < 2 (0, nil) is returned.
//
// NOTE: Run time for large values of n (above about 2^1e6 ~= 1e300000) can be
// significant and/or unacceptabe.  For any smaller values of n the function
// typically performs in sub second time.  For "small" values of n (cca bellow
// 2^1e3 ~= 1e300) the same can be easily below 10 µs.
//
// A special (and trivial) case of b == 2 is handled separately and performs
// much faster.
func PowerizeBigInt(b, n *big.Int) (e uint32, p *big.Int) {
	switch {
	case b.Cmp(_2) < 0 || n.Sign() < 0:
		return
	case n.Sign() == 0 || n.Cmp(_1) == 0:
		return 0, big.NewInt(1)
	case b.Cmp(_2) == 0:
		p = big.NewInt(0)
		e = uint32(n.BitLen() - 1)
		p.SetBit(p, int(e), 1)
		if p.Cmp(n) < 0 {
			p.Mul(p, _2)
			e++
		}
		return
	}

	bw := b.BitLen()
	nw := n.BitLen()
	p = big.NewInt(1)
	var bb, r big.Int
	for {
		switch p.Cmp(n) {
		case -1:
			x := uint32((nw - p.BitLen()) / bw)
			if x == 0 {
				x = 1
			}
			e += x
			switch x {
			case 1:
				p.Mul(p, b)
			default:
				r.Set(_1)
				bb.Set(b)
				e := x
				for {
					if e&1 != 0 {
						r.Mul(&r, &bb)
					}
					if e >>= 1; e == 0 {
						break
					}

					bb.Mul(&bb, &bb)
				}
				p.Mul(p, &r)
			}
		case 0, 1:
			return
		}
	}
}

// PowerizeUint32BigInt returns (e, p) such that e is the smallest number for
// which p == b^e is greater or equal n. For n < 0 or b < 2 (0, nil) is
// returned.
//
// More info: see PowerizeBigInt.
func PowerizeUint32BigInt(b uint32, n *big.Int) (e uint32, p *big.Int) {
	switch {
	case b < 2 || n.Sign() < 0:
		return
	case n.Sign() == 0 || n.Cmp(_1) == 0:
		return 0, big.NewInt(1)
	case b == 2:
		p = big.NewInt(0)
		e = uint32(n.BitLen() - 1)
		p.SetBit(p, int(e), 1)
		if p.Cmp(n) < 0 {
			p.Mul(p, _2)
			e++
		}
		return
	}

	var bb big.Int
	bb.SetInt64(int64(b))
	return PowerizeBigInt(&bb, n)
}

/*
ProbablyPrimeUint32 returns true if n is prime or n is a pseudoprime to base a.
It implements the Miller-Rabin primality test for one specific value of 'a' and
k == 1.

Wrt pseudocode shown at
http://en.wikipedia.org/wiki/Miller-Rabin_primality_test#Algorithm_and_running_time

 Input: n > 3, an odd integer to be tested for primality;
 Input: k, a parameter that determines the accuracy of the test
 Output: composite if n is composite, otherwise probably prime
 write n − 1 as 2^s·d with d odd by factoring powers of 2 from n − 1
 LOOP: repeat k times:
    pick a random integer a in the range [2, n − 2]
    x ← a^d mod n
    if x = 1 or x = n − 1 then do next LOOP
    for r = 1 .. s − 1
       x ← x^2 mod n
       if x = 1 then return composite
       if x = n − 1 then do next LOOP
    return composite
 return probably prime

... this function behaves like passing 1 for 'k' and additionally a
fixed/non-random 'a'.  Otherwise it's the same algorithm.

See also: http://mathworld.wolfram.com/Rabin-MillerStrongPseudoprimeTest.html
*/
func ProbablyPrimeUint32(n, a uint32) bool {
	d, s := n-1, 0
	for ; d&1 == 0; d, s = d>>1, s+1 {
	}
	x := uint64(ModPowUint32(a, d, n))
	if x == 1 || uint32(x) == n-1 {
		return true
	}

	for ; s > 1; s-- {
		if x = x * x % uint64(n); x == 1 {
			return false
		}

		if uint32(x) == n-1 {
			return true
		}
	}
	return false
}

// ProbablyPrimeUint64_32 returns true if n is prime or n is a pseudoprime to
// base a. It implements the Miller-Rabin primality test for one specific value
// of 'a' and k == 1.  See also ProbablyPrimeUint32.
func ProbablyPrimeUint64_32(n uint64, a uint32) bool {
	d, s := n-1, 0
	for ; d&1 == 0; d, s = d>>1, s+1 {
	}
	x := ModPowUint64(uint64(a), d, n)
	if x == 1 || x == n-1 {
		return true
	}

	bx, bn := big.NewInt(0).SetUint64(x), big.NewInt(0).SetUint64(n)
	for ; s > 1; s-- {
		if x = bx.Mod(bx.Mul(bx, bx), bn).Uint64(); x == 1 {
			return false
		}

		if x == n-1 {
			return true
		}
	}
	return false
}

// ProbablyPrimeBigInt_32 returns true if n is prime or n is a pseudoprime to
// base a. It implements the Miller-Rabin primality test for one specific value
// of 'a' and k == 1.  See also ProbablyPrimeUint32.
func ProbablyPrimeBigInt_32(n *big.Int, a uint32) bool {
	var d big.Int
	d.Set(n)
	d.Sub(&d, _1) // d <- n-1
	s := 0
	for ; d.Bit(s) == 0; s++ {
	}
	nMinus1 := big.NewInt(0).Set(&d)
	d.Rsh(&d, uint(s))

	x := ModPowBigInt(big.NewInt(int64(a)), &d, n)
	if x.Cmp(_1) == 0 || x.Cmp(nMinus1) == 0 {
		return true
	}

	for ; s > 1; s-- {
		if x = x.Mod(x.Mul(x, x), n); x.Cmp(_1) == 0 {
			return false
		}

		if x.Cmp(nMinus1) == 0 {
			return true
		}
	}
	return false
}

// ProbablyPrimeBigInt returns true if n is prime or n is a pseudoprime to base
// a. It implements the Miller-Rabin primality test for one specific value of
// 'a' and k == 1.  See also ProbablyPrimeUint32.
func ProbablyPrimeBigInt(n, a *big.Int) bool {
	var d big.Int
	d.Set(n)
	d.Sub(&d, _1) // d <- n-1
	s := 0
	for ; d.Bit(s) == 0; s++ {
	}
	nMinus1 := big.NewInt(0).Set(&d)
	d.Rsh(&d, uint(s))

	x := ModPowBigInt(a, &d, n)
	if x.Cmp(_1) == 0 || x.Cmp(nMinus1) == 0 {
		return true
	}

	for ; s > 1; s-- {
		if x = x.Mod(x.Mul(x, x), n); x.Cmp(_1) == 0 {
			return false
		}

		if x.Cmp(nMinus1) == 0 {
			return true
		}
	}
	return false
}

// Max returns the larger of a and b.
func Max(a, b int) int {
	if a > b {
		return a
	}

	return b
}

// Min returns the smaller of a and b.
func Min(a, b int) int {
	if a < b {
		return a
	}

	return b
}

// MaxPtr returns a pointer to the larger of a and b, or nil.
func MaxPtr(a, b *int) *int {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a > *b {
		return a
	}

	return b
}

// MinPtr returns a pointer to the smaller of a and b, or nil.
func MinPtr(a, b *int) *int {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a < *b {
		return a
	}

	return b
}

// MaxVal returns the largest argument passed.
func MaxVal(val int, vals ...int) int {
	res := val
	for _, v := range vals {
		if v > res {
			res = v
		}
	}
	return res
}

// MinVal returns the smallest argument passed.
func MinVal(val int, vals ...int) int {
	res := val
	for _, v := range vals {
		if v < res {
			res = v
		}
	}
	return res
}

// Clamp returns a value restricted between lo and hi.
func Clamp(v, lo, hi int) int {
	return Min(Max(v, lo), hi)
}

// UMax returns the larger of a and b.
func UMax(a, b uint) uint {
	if a > b {
		return a
	}

	return b
}

// UMin returns the smaller of a and b.
func UMin(a, b uint) uint {
	if a < b {
		return a
	}

	return b
}

// UMaxPtr returns a pointer to the larger of a and b, or nil.
func UMaxPtr(a, b *uint) *uint {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a > *b {
		return a
	}

	return b
}

// UMinPtr returns a pointer to the smaller of a and b, or nil.
func UMinPtr(a, b *uint) *uint {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a < *b {
		return a
	}

	return b
}

// UMaxVal returns the largest argument passed.
func UMaxVal(val uint, vals ...uint) uint {
	res := val
	for _, v := range vals {
		if v > res {
			res = v
		}
	}
	return res
}

// UMinVal returns the smallest argument passed.
func UMinVal(val uint, vals ...uint) uint {
	res := val
	for _, v := range vals {
		if v < res {
			res = v
		}
	}
	return res
}

// UClamp returns a value restricted between lo and hi.
func UClamp(v, lo, hi uint) uint {
	return UMin(UMax(v, lo), hi)
}

// MaxByte returns the larger of a and b.
func MaxByte(a, b byte) byte {
	if a > b {
		return a
	}

	return b
}

// MinByte returns the smaller of a and b.
func MinByte(a, b byte) byte {
	if a < b {
		return a
	}

	return b
}

// MaxBytePtr returns a pointer to the larger of a and b, or nil.
func MaxBytePtr(a, b *byte) *byte {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a > *b {
		return a
	}

	return b
}

// MinBytePtr returns a pointer to the smaller of a and b, or nil.
func MinBytePtr(a, b *byte) *byte {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a < *b {
		return a
	}

	return b
}

// MaxByteVal returns the largest argument passed.
func MaxByteVal(val byte, vals ...byte) byte {
	res := val
	for _, v := range vals {
		if v > res {
			res = v
		}
	}
	return res
}

// MinByteVal returns the smallest argument passed.
func MinByteVal(val byte, vals ...byte) byte {
	res := val
	for _, v := range vals {
		if v < res {
			res = v
		}
	}
	return res
}

// ClampByte returns a value restricted between lo and hi.
func ClampByte(v, lo, hi byte) byte {
	return MinByte(MaxByte(v, lo), hi)
}

// MaxInt8 returns the larger of a and b.
func MaxInt8(a, b int8) int8 {
	if a > b {
		return a
	}

	return b
}

// MinInt8 returns the smaller of a and b.
func MinInt8(a, b int8) int8 {
	if a < b {
		return a
	}

	return b
}

// MaxInt8Ptr returns a pointer to the larger of a and b, or nil.
func MaxInt8Ptr(a, b *int8) *int8 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a > *b {
		return a
	}

	return b
}

// MinInt8Ptr returns a pointer to the smaller of a and b, or nil.
func MinInt8Ptr(a, b *int8) *int8 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a < *b {
		return a
	}

	return b
}

// MaxInt8Val returns the largest argument passed.
func MaxInt8Val(val int8, vals ...int8) int8 {
	res := val
	for _, v := range vals {
		if v > res {
			res = v
		}
	}
	return res
}

// MinInt8Val returns the smallest argument passed.
func MinInt8Val(val int8, vals ...int8) int8 {
	res := val
	for _, v := range vals {
		if v < res {
			res = v
		}
	}
	return res
}

// ClampInt8 returns a value restricted between lo and hi.
func ClampInt8(v, lo, hi int8) int8 {
	return MinInt8(MaxInt8(v, lo), hi)
}

// MaxUint16 returns the larger of a and b.
func MaxUint16(a, b uint16) uint16 {
	if a > b {
		return a
	}

	return b
}

// MinUint16 returns the smaller of a and b.
func MinUint16(a, b uint16) uint16 {
	if a < b {
		return a
	}

	return b
}

// MaxUint16Ptr returns a pointer to the larger of a and b, or nil.
func MaxUint16Ptr(a, b *uint16) *uint16 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a > *b {
		return a
	}

	return b
}

// MinUint16Ptr returns a pointer to the smaller of a and b, or nil.
func MinUint16Ptr(a, b *uint16) *uint16 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a < *b {
		return a
	}

	return b
}

// MaxUint16Val returns the largest argument passed.
func MaxUint16Val(val uint16, vals ...uint16) uint16 {
	res := val
	for _, v := range vals {
		if v > res {
			res = v
		}
	}
	return res
}

// MinUint16Val returns the smallest argument passed.
func MinUint16Val(val uint16, vals ...uint16) uint16 {
	res := val
	for _, v := range vals {
		if v < res {
			res = v
		}
	}
	return res
}

// ClampUint16 returns a value restricted between lo and hi.
func ClampUint16(v, lo, hi uint16) uint16 {
	return MinUint16(MaxUint16(v, lo), hi)
}

// MaxInt16 returns the larger of a and b.
func MaxInt16(a, b int16) int16 {
	if a > b {
		return a
	}

	return b
}

// MinInt16 returns the smaller of a and b.
func MinInt16(a, b int16) int16 {
	if a < b {
		return a
	}

	return b
}

// MaxInt16Ptr returns a pointer to the larger of a and b, or nil.
func MaxInt16Ptr(a, b *int16) *int16 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a > *b {
		return a
	}

	return b
}

// MinInt16Ptr returns a pointer to the smaller of a and b, or nil.
func MinInt16Ptr(a, b *int16) *int16 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a < *b {
		return a
	}

	return b
}

// MaxInt16Val returns the largest argument passed.
func MaxInt16Val(val int16, vals ...int16) int16 {
	res := val
	for _, v := range vals {
		if v > res {
			res = v
		}
	}
	return res
}

// MinInt16Val returns the smallest argument passed.
func MinInt16Val(val int16, vals ...int16) int16 {
	res := val
	for _, v := range vals {
		if v < res {
			res = v
		}
	}
	return res
}

// ClampInt16 returns a value restricted between lo and hi.
func ClampInt16(v, lo, hi int16) int16 {
	return MinInt16(MaxInt16(v, lo), hi)
}

// MaxUint32 returns the larger of a and b.
func MaxUint32(a, b uint32) uint32 {
	if a > b {
		return a
	}

	return b
}

// MinUint32 returns the smaller of a and b.
func MinUint32(a, b uint32) uint32 {
	if a < b {
		return a
	}

	return b
}

// MaxUint32Ptr returns a pointer to the larger of a and b, or nil.
func MaxUint32Ptr(a, b *uint32) *uint32 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a > *b {
		return a
	}

	return b
}

// MinUint32Ptr returns a pointer to the smaller of a and b, or nil.
func MinUint32Ptr(a, b *uint32) *uint32 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a < *b {
		return a
	}

	return b
}

// MaxUint32Val returns the largest argument passed.
func MaxUint32Val(val uint32, vals ...uint32) uint32 {
	res := val
	for _, v := range vals {
		if v > res {
			res = v
		}
	}
	return res
}

// MinUint32Val returns the smallest argument passed.
func MinUint32Val(val uint32, vals ...uint32) uint32 {
	res := val
	for _, v := range vals {
		if v < res {
			res = v
		}
	}
	return res
}

// ClampUint32 returns a value restricted between lo and hi.
func ClampUint32(v, lo, hi uint32) uint32 {
	return MinUint32(MaxUint32(v, lo), hi)
}

// MaxInt32 returns the larger of a and b.
func MaxInt32(a, b int32) int32 {
	if a > b {
		return a
	}

	return b
}

// MinInt32 returns the smaller of a and b.
func MinInt32(a, b int32) int32 {
	if a < b {
		return a
	}

	return b
}

// MaxInt32Ptr returns a pointer to the larger of a and b, or nil.
func MaxInt32Ptr(a, b *int32) *int32 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a > *b {
		return a
	}

	return b
}

// MinInt32Ptr returns a pointer to the smaller of a and b, or nil.
func MinInt32Ptr(a, b *int32) *int32 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a < *b {
		return a
	}

	return b
}

// MaxInt32Val returns the largest argument passed.
func MaxInt32Val(val int32, vals ...int32) int32 {
	res := val
	for _, v := range vals {
		if v > res {
			res = v
		}
	}
	return res
}

// MinInt32Val returns the smallest argument passed.
func MinInt32Val(val int32, vals ...int32) int32 {
	res := val
	for _, v := range vals {
		if v < res {
			res = v
		}
	}
	return res
}

// ClampInt32 returns a value restricted between lo and hi.
func ClampInt32(v, lo, hi int32) int32 {
	return MinInt32(MaxInt32(v, lo), hi)
}

// MaxUint64 returns the larger of a and b.
func MaxUint64(a, b uint64) uint64 {
	if a > b {
		return a
	}

	return b
}

// MinUint64 returns the smaller of a and b.
func MinUint64(a, b uint64) uint64 {
	if a < b {
		return a
	}

	return b
}

// MaxUint64Ptr returns a pointer to the larger of a and b, or nil.
func MaxUint64Ptr(a, b *uint64) *uint64 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a > *b {
		return a
	}

	return b
}

// MinUint64Ptr returns a pointer to the smaller of a and b, or nil.
func MinUint64Ptr(a, b *uint64) *uint64 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a < *b {
		return a
	}

	return b
}

// MaxUint64Val returns the largest argument passed.
func MaxUint64Val(val uint64, vals ...uint64) uint64 {
	res := val
	for _, v := range vals {
		if v > res {
			res = v
		}
	}
	return res
}

// MinUint64Val returns the smallest argument passed.
func MinUint64Val(val uint64, vals ...uint64) uint64 {
	res := val
	for _, v := range vals {
		if v < res {
			res = v
		}
	}
	return res
}

// ClampUint64 returns a value restricted between lo and hi.
func ClampUint64(v, lo, hi uint64) uint64 {
	return MinUint64(MaxUint64(v, lo), hi)
}

// MaxInt64 returns the larger of a and b.
func MaxInt64(a, b int64) int64 {
	if a > b {
		return a
	}

	return b
}

// MinInt64 returns the smaller of a and b.
func MinInt64(a, b int64) int64 {
	if a < b {
		return a
	}

	return b
}

// MaxInt64Ptr returns a pointer to the larger of a and b, or nil.
func MaxInt64Ptr(a, b *int64) *int64 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a > *b {
		return a
	}

	return b
}

// MinInt64Ptr returns a pointer to the smaller of a and b, or nil.
func MinInt64Ptr(a, b *int64) *int64 {
	if a == nil {
		return b
	}
	if b == nil {
		return a
	}
	if *a < *b {
		return a
	}

	return b
}

// MaxInt64Val returns the largest argument passed.
func MaxInt64Val(val int64, vals ...int64) int64 {
	res := val
	for _, v := range vals {
		if v > res {
			res = v
		}
	}
	return res
}

// MinInt64Val returns the smallest argument passed.
func MinInt64Val(val int64, vals ...int64) int64 {
	res := val
	for _, v := range vals {
		if v < res {
			res = v
		}
	}
	return res
}

// ClampInt64 returns a value restricted between lo and hi.
func ClampInt64(v, lo, hi int64) int64 {
	return MinInt64(MaxInt64(v, lo), hi)
}

// ToBase produces n in base b. For example
//
// 	ToBase(2047, 22) -> [1, 5, 4]
//
//	1 * 22^0           1
//	5 * 22^1         110
//	4 * 22^2        1936
//	                ----
//	                2047
//
// ToBase panics for bases < 2.
func ToBase(n *big.Int, b int) []int {
	var nn big.Int
	nn.Set(n)
	if b < 2 {
		panic("invalid base")
	}

	k := 1
	switch nn.Sign() {
	case -1:
		nn.Neg(&nn)
		k = -1
	case 0:
		return []int{0}
	}

	bb := big.NewInt(int64(b))
	var r []int
	rem := big.NewInt(0)
	for nn.Sign() != 0 {
		nn.QuoRem(&nn, bb, rem)
		r = append(r, k*int(rem.Int64()))
	}
	return r
}

// CheckAddInt64 returns the a+b and an indicator that the result is greater
// than math.MaxInt64.
func CheckAddInt64(a, b int64) (sum int64, gt bool) {
	return a + b, a > 0 && b > math.MaxInt64-a || a < 0 && b < math.MinInt64-a
}

// CheckSubInt64 returns a-b and an indicator that the result is less than than
// math.MinInt64.
func CheckSubInt64(a, b int64) (sum int64, lt bool) {
	return a - b, a > 0 && a-math.MaxInt64 > b || a < 0 && a-math.MinInt64 < b
}

// AddOverflowInt8 returns a + b and an indication whether the addition
// overflowed the int8 range.
func AddOverflowInt8(a, b int8) (r int8, ovf bool) {
	r = a + b
	if a > 0 && b > 0 {
		return r, uint8(r) > math.MaxInt8
	}

	if a < 0 && b < 0 {
		return r, uint8(r) <= math.MaxInt8
	}

	return r, false
}

// AddOverflowInt16 returns a + b and an indication whether the addition
// overflowed the int16 range.
func AddOverflowInt16(a, b int16) (r int16, ovf bool) {
	r = a + b
	if a > 0 && b > 0 {
		return r, uint16(r) > math.MaxInt16
	}

	if a < 0 && b < 0 {
		return r, uint16(r) <= math.MaxInt16
	}

	return r, false
}

// AddOverflowInt32 returns a + b and an indication whether the addition
// overflowed the int32 range.
func AddOverflowInt32(a, b int32) (r int32, ovf bool) {
	r = a + b
	if a > 0 && b > 0 {
		return r, uint32(r) > math.MaxInt32
	}

	if a < 0 && b < 0 {
		return r, uint32(r) <= math.MaxInt32
	}

	return r, false
}

// AddOverflowInt64 returns a + b and an indication whether the addition
// overflowed the int64 range.
func AddOverflowInt64(a, b int64) (r int64, ovf bool) {
	r = a + b
	if a > 0 && b > 0 {
		return r, uint64(r) > math.MaxInt64
	}

	if a < 0 && b < 0 {
		return r, uint64(r) <= math.MaxInt64
	}

	return r, false
}

// SubOverflowInt8 returns a - b and an indication whether the subtraction
// overflowed the int8 range.
func SubOverflowInt8(a, b int8) (r int8, ovf bool) {
	r = a - b
	if a >= 0 && b < 0 {
		return r, uint8(r) >= math.MaxInt8+1
	}

	if a < 0 && b > 0 {
		return r, uint8(r) <= math.MaxInt8
	}

	return r, false
}

// SubOverflowInt16 returns a - b and an indication whether the subtraction
// overflowed the int16 range.
func SubOverflowInt16(a, b int16) (r int16, ovf bool) {
	r = a - b
	if a >= 0 && b < 0 {
		return r, uint16(r) >= math.MaxInt16+1
	}

	if a < 0 && b > 0 {
		return r, uint16(r) <= math.MaxInt16
	}

	return r, false
}

// SubOverflowInt32 returns a - b and an indication whether the subtraction
// overflowed the int32 range.
func SubOverflowInt32(a, b int32) (r int32, ovf bool) {
	r = a - b
	if a >= 0 && b < 0 {
		return r, uint32(r) >= math.MaxInt32+1
	}

	if a < 0 && b > 0 {
		return r, uint32(r) <= math.MaxInt32
	}

	return r, false
}

// SubOverflowInt64 returns a - b and an indication whether the subtraction
// overflowed the int64 range.
func SubOverflowInt64(a, b int64) (r int64, ovf bool) {
	r = a - b
	if a >= 0 && b < 0 {
		return r, uint64(r) >= math.MaxInt64+1
	}

	if a < 0 && b > 0 {
		return r, uint64(r) <= math.MaxInt64
	}

	return r, false
}

// MulOverflowInt8 returns a * b and an indication whether the product
// overflowed the int8 range.
func MulOverflowInt8(a, b int8) (r int8, ovf bool) {
	if a == 0 || b == 0 {
		return 0, false
	}

	z := int16(a) * int16(b)
	return int8(z), z < math.MinInt8 || z > math.MaxInt8
}

// MulOverflowInt16 returns a * b and an indication whether the product
// overflowed the int16 range.
func MulOverflowInt16(a, b int16) (r int16, ovf bool) {
	if a == 0 || b == 0 {
		return 0, false
	}

	z := int32(a) * int32(b)
	return int16(z), z < math.MinInt16 || z > math.MaxInt16
}

// MulOverflowInt32 returns a * b and an indication whether the product
// overflowed the int32 range.
func MulOverflowInt32(a, b int32) (r int32, ovf bool) {
	if a == 0 || b == 0 {
		return 0, false
	}

	z := int64(a) * int64(b)
	return int32(z), z < math.MinInt32 || z > math.MaxInt32
}

// MulOverflowInt64 returns a * b and an indication whether the product
// overflowed the int64 range.
func MulOverflowInt64(a, b int64) (r int64, ovf bool) {
	// https://groups.google.com/g/golang-nuts/c/h5oSN5t3Au4/m/KaNQREhZh0QJ
	const mostPositive = 1<<63 - 1
	const mostNegative = -(mostPositive + 1)
	r = a * b
	if a == 0 || b == 0 || a == 1 || b == 1 {
		return r, false
	}

	if a == mostNegative || b == mostNegative {
		return r, true
	}

	return r, r/b != a
}