Source file src/math/big/nat_test.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package big
     6  
     7  import (
     8  	"fmt"
     9  	"math"
    10  	"runtime"
    11  	"strings"
    12  	"testing"
    13  )
    14  
    15  var cmpTests = []struct {
    16  	x, y nat
    17  	r    int
    18  }{
    19  	{nil, nil, 0},
    20  	{nil, nat(nil), 0},
    21  	{nat(nil), nil, 0},
    22  	{nat(nil), nat(nil), 0},
    23  	{nat{0}, nat{0}, 0},
    24  	{nat{0}, nat{1}, -1},
    25  	{nat{1}, nat{0}, 1},
    26  	{nat{1}, nat{1}, 0},
    27  	{nat{0, _M}, nat{1}, 1},
    28  	{nat{1}, nat{0, _M}, -1},
    29  	{nat{1, _M}, nat{0, _M}, 1},
    30  	{nat{0, _M}, nat{1, _M}, -1},
    31  	{nat{16, 571956, 8794, 68}, nat{837, 9146, 1, 754489}, -1},
    32  	{nat{34986, 41, 105, 1957}, nat{56, 7458, 104, 1957}, 1},
    33  }
    34  
    35  func TestCmp(t *testing.T) {
    36  	for i, a := range cmpTests {
    37  		r := a.x.cmp(a.y)
    38  		if r != a.r {
    39  			t.Errorf("#%d got r = %v; want %v", i, r, a.r)
    40  		}
    41  	}
    42  }
    43  
    44  type funNN func(z, x, y nat) nat
    45  type argNN struct {
    46  	z, x, y nat
    47  }
    48  
    49  var sumNN = []argNN{
    50  	{},
    51  	{nat{1}, nil, nat{1}},
    52  	{nat{1111111110}, nat{123456789}, nat{987654321}},
    53  	{nat{0, 0, 0, 1}, nil, nat{0, 0, 0, 1}},
    54  	{nat{0, 0, 0, 1111111110}, nat{0, 0, 0, 123456789}, nat{0, 0, 0, 987654321}},
    55  	{nat{0, 0, 0, 1}, nat{0, 0, _M}, nat{0, 0, 1}},
    56  }
    57  
    58  var prodNN = []argNN{
    59  	{},
    60  	{nil, nil, nil},
    61  	{nil, nat{991}, nil},
    62  	{nat{991}, nat{991}, nat{1}},
    63  	{nat{991 * 991}, nat{991}, nat{991}},
    64  	{nat{0, 0, 991 * 991}, nat{0, 991}, nat{0, 991}},
    65  	{nat{1 * 991, 2 * 991, 3 * 991, 4 * 991}, nat{1, 2, 3, 4}, nat{991}},
    66  	{nat{4, 11, 20, 30, 20, 11, 4}, nat{1, 2, 3, 4}, nat{4, 3, 2, 1}},
    67  	// 3^100 * 3^28 = 3^128
    68  	{
    69  		natFromString("11790184577738583171520872861412518665678211592275841109096961"),
    70  		natFromString("515377520732011331036461129765621272702107522001"),
    71  		natFromString("22876792454961"),
    72  	},
    73  	// z = 111....1 (70000 digits)
    74  	// x = 10^(99*700) + ... + 10^1400 + 10^700 + 1
    75  	// y = 111....1 (700 digits, larger than Karatsuba threshold on 32-bit and 64-bit)
    76  	{
    77  		natFromString(strings.Repeat("1", 70000)),
    78  		natFromString("1" + strings.Repeat(strings.Repeat("0", 699)+"1", 99)),
    79  		natFromString(strings.Repeat("1", 700)),
    80  	},
    81  	// z = 111....1 (20000 digits)
    82  	// x = 10^10000 + 1
    83  	// y = 111....1 (10000 digits)
    84  	{
    85  		natFromString(strings.Repeat("1", 20000)),
    86  		natFromString("1" + strings.Repeat("0", 9999) + "1"),
    87  		natFromString(strings.Repeat("1", 10000)),
    88  	},
    89  }
    90  
    91  func natFromString(s string) nat {
    92  	x, _, _, err := nat(nil).scan(strings.NewReader(s), 0, false)
    93  	if err != nil {
    94  		panic(err)
    95  	}
    96  	return x
    97  }
    98  
    99  func TestSet(t *testing.T) {
   100  	for _, a := range sumNN {
   101  		z := nat(nil).set(a.z)
   102  		if z.cmp(a.z) != 0 {
   103  			t.Errorf("got z = %v; want %v", z, a.z)
   104  		}
   105  	}
   106  }
   107  
   108  func testFunNN(t *testing.T, msg string, f funNN, a argNN) {
   109  	z := f(nil, a.x, a.y)
   110  	if z.cmp(a.z) != 0 {
   111  		t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, z, a.z)
   112  	}
   113  }
   114  
   115  func TestFunNN(t *testing.T) {
   116  	for _, a := range sumNN {
   117  		arg := a
   118  		testFunNN(t, "add", nat.add, arg)
   119  
   120  		arg = argNN{a.z, a.y, a.x}
   121  		testFunNN(t, "add symmetric", nat.add, arg)
   122  
   123  		arg = argNN{a.x, a.z, a.y}
   124  		testFunNN(t, "sub", nat.sub, arg)
   125  
   126  		arg = argNN{a.y, a.z, a.x}
   127  		testFunNN(t, "sub symmetric", nat.sub, arg)
   128  	}
   129  
   130  	for _, a := range prodNN {
   131  		arg := a
   132  		testFunNN(t, "mul", nat.mul, arg)
   133  
   134  		arg = argNN{a.z, a.y, a.x}
   135  		testFunNN(t, "mul symmetric", nat.mul, arg)
   136  	}
   137  }
   138  
   139  var mulRangesN = []struct {
   140  	a, b uint64
   141  	prod string
   142  }{
   143  	{0, 0, "0"},
   144  	{1, 1, "1"},
   145  	{1, 2, "2"},
   146  	{1, 3, "6"},
   147  	{10, 10, "10"},
   148  	{0, 100, "0"},
   149  	{0, 1e9, "0"},
   150  	{1, 0, "1"},                    // empty range
   151  	{100, 1, "1"},                  // empty range
   152  	{1, 10, "3628800"},             // 10!
   153  	{1, 20, "2432902008176640000"}, // 20!
   154  	{1, 100,
   155  		"933262154439441526816992388562667004907159682643816214685929" +
   156  			"638952175999932299156089414639761565182862536979208272237582" +
   157  			"51185210916864000000000000000000000000", // 100!
   158  	},
   159  	{math.MaxUint64 - 0, math.MaxUint64, "18446744073709551615"},
   160  	{math.MaxUint64 - 1, math.MaxUint64, "340282366920938463408034375210639556610"},
   161  	{math.MaxUint64 - 2, math.MaxUint64, "6277101735386680761794095221682035635525021984684230311930"},
   162  	{math.MaxUint64 - 3, math.MaxUint64, "115792089237316195360799967654821100226821973275796746098729803619699194331160"},
   163  }
   164  
   165  func TestMulRangeN(t *testing.T) {
   166  	for i, r := range mulRangesN {
   167  		prod := string(nat(nil).mulRange(r.a, r.b).utoa(10))
   168  		if prod != r.prod {
   169  			t.Errorf("#%d: got %s; want %s", i, prod, r.prod)
   170  		}
   171  	}
   172  }
   173  
   174  // allocBytes returns the number of bytes allocated by invoking f.
   175  func allocBytes(f func()) uint64 {
   176  	var stats runtime.MemStats
   177  	runtime.ReadMemStats(&stats)
   178  	t := stats.TotalAlloc
   179  	f()
   180  	runtime.ReadMemStats(&stats)
   181  	return stats.TotalAlloc - t
   182  }
   183  
   184  // TestMulUnbalanced tests that multiplying numbers of different lengths
   185  // does not cause deep recursion and in turn allocate too much memory.
   186  // Test case for issue 3807.
   187  func TestMulUnbalanced(t *testing.T) {
   188  	defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
   189  	x := rndNat(50000)
   190  	y := rndNat(40)
   191  	allocSize := allocBytes(func() {
   192  		nat(nil).mul(x, y)
   193  	})
   194  	inputSize := uint64(len(x)+len(y)) * _S
   195  	if ratio := allocSize / uint64(inputSize); ratio > 10 {
   196  		t.Errorf("multiplication uses too much memory (%d > %d times the size of inputs)", allocSize, ratio)
   197  	}
   198  }
   199  
   200  // rndNat returns a random nat value >= 0 of (usually) n words in length.
   201  // In extremely unlikely cases it may be smaller than n words if the top-
   202  // most words are 0.
   203  func rndNat(n int) nat {
   204  	return nat(rndV(n)).norm()
   205  }
   206  
   207  // rndNat1 is like rndNat but the result is guaranteed to be > 0.
   208  func rndNat1(n int) nat {
   209  	x := nat(rndV(n)).norm()
   210  	if len(x) == 0 {
   211  		x.setWord(1)
   212  	}
   213  	return x
   214  }
   215  
   216  func BenchmarkMul(b *testing.B) {
   217  	mulx := rndNat(1e4)
   218  	muly := rndNat(1e4)
   219  	b.ResetTimer()
   220  	for i := 0; i < b.N; i++ {
   221  		var z nat
   222  		z.mul(mulx, muly)
   223  	}
   224  }
   225  
   226  func benchmarkNatMul(b *testing.B, nwords int) {
   227  	x := rndNat(nwords)
   228  	y := rndNat(nwords)
   229  	var z nat
   230  	b.ResetTimer()
   231  	for i := 0; i < b.N; i++ {
   232  		z.mul(x, y)
   233  	}
   234  }
   235  
   236  var mulBenchSizes = []int{10, 100, 1000, 10000, 100000}
   237  
   238  func BenchmarkNatMul(b *testing.B) {
   239  	for _, n := range mulBenchSizes {
   240  		if isRaceBuilder && n > 1e3 {
   241  			continue
   242  		}
   243  		b.Run(fmt.Sprintf("%d", n), func(b *testing.B) {
   244  			benchmarkNatMul(b, n)
   245  		})
   246  	}
   247  }
   248  
   249  func TestNLZ(t *testing.T) {
   250  	var x Word = _B >> 1
   251  	for i := 0; i <= _W; i++ {
   252  		if int(nlz(x)) != i {
   253  			t.Errorf("failed at %x: got %d want %d", x, nlz(x), i)
   254  		}
   255  		x >>= 1
   256  	}
   257  }
   258  
   259  type shiftTest struct {
   260  	in    nat
   261  	shift uint
   262  	out   nat
   263  }
   264  
   265  var leftShiftTests = []shiftTest{
   266  	{nil, 0, nil},
   267  	{nil, 1, nil},
   268  	{natOne, 0, natOne},
   269  	{natOne, 1, natTwo},
   270  	{nat{1 << (_W - 1)}, 1, nat{0}},
   271  	{nat{1 << (_W - 1), 0}, 1, nat{0, 1}},
   272  }
   273  
   274  func TestShiftLeft(t *testing.T) {
   275  	for i, test := range leftShiftTests {
   276  		var z nat
   277  		z = z.shl(test.in, test.shift)
   278  		for j, d := range test.out {
   279  			if j >= len(z) || z[j] != d {
   280  				t.Errorf("#%d: got: %v want: %v", i, z, test.out)
   281  				break
   282  			}
   283  		}
   284  	}
   285  }
   286  
   287  var rightShiftTests = []shiftTest{
   288  	{nil, 0, nil},
   289  	{nil, 1, nil},
   290  	{natOne, 0, natOne},
   291  	{natOne, 1, nil},
   292  	{natTwo, 1, natOne},
   293  	{nat{0, 1}, 1, nat{1 << (_W - 1)}},
   294  	{nat{2, 1, 1}, 1, nat{1<<(_W-1) + 1, 1 << (_W - 1)}},
   295  }
   296  
   297  func TestShiftRight(t *testing.T) {
   298  	for i, test := range rightShiftTests {
   299  		var z nat
   300  		z = z.shr(test.in, test.shift)
   301  		for j, d := range test.out {
   302  			if j >= len(z) || z[j] != d {
   303  				t.Errorf("#%d: got: %v want: %v", i, z, test.out)
   304  				break
   305  			}
   306  		}
   307  	}
   308  }
   309  
   310  func BenchmarkZeroShifts(b *testing.B) {
   311  	x := rndNat(800)
   312  
   313  	b.Run("Shl", func(b *testing.B) {
   314  		for i := 0; i < b.N; i++ {
   315  			var z nat
   316  			z.shl(x, 0)
   317  		}
   318  	})
   319  	b.Run("ShlSame", func(b *testing.B) {
   320  		for i := 0; i < b.N; i++ {
   321  			x.shl(x, 0)
   322  		}
   323  	})
   324  
   325  	b.Run("Shr", func(b *testing.B) {
   326  		for i := 0; i < b.N; i++ {
   327  			var z nat
   328  			z.shr(x, 0)
   329  		}
   330  	})
   331  	b.Run("ShrSame", func(b *testing.B) {
   332  		for i := 0; i < b.N; i++ {
   333  			x.shr(x, 0)
   334  		}
   335  	})
   336  }
   337  
   338  type modWTest struct {
   339  	in       string
   340  	dividend string
   341  	out      string
   342  }
   343  
   344  var modWTests32 = []modWTest{
   345  	{"23492635982634928349238759823742", "252341", "220170"},
   346  }
   347  
   348  var modWTests64 = []modWTest{
   349  	{"6527895462947293856291561095690465243862946", "524326975699234", "375066989628668"},
   350  }
   351  
   352  func runModWTests(t *testing.T, tests []modWTest) {
   353  	for i, test := range tests {
   354  		in, _ := new(Int).SetString(test.in, 10)
   355  		d, _ := new(Int).SetString(test.dividend, 10)
   356  		out, _ := new(Int).SetString(test.out, 10)
   357  
   358  		r := in.abs.modW(d.abs[0])
   359  		if r != out.abs[0] {
   360  			t.Errorf("#%d failed: got %d want %s", i, r, out)
   361  		}
   362  	}
   363  }
   364  
   365  func TestModW(t *testing.T) {
   366  	if _W >= 32 {
   367  		runModWTests(t, modWTests32)
   368  	}
   369  	if _W >= 64 {
   370  		runModWTests(t, modWTests64)
   371  	}
   372  }
   373  
   374  var montgomeryTests = []struct {
   375  	x, y, m      string
   376  	k0           uint64
   377  	out32, out64 string
   378  }{
   379  	{
   380  		"0xffffffffffffffffffffffffffffffffffffffffffffffffe",
   381  		"0xffffffffffffffffffffffffffffffffffffffffffffffffe",
   382  		"0xfffffffffffffffffffffffffffffffffffffffffffffffff",
   383  		1,
   384  		"0x1000000000000000000000000000000000000000000",
   385  		"0x10000000000000000000000000000000000",
   386  	},
   387  	{
   388  		"0x000000000ffffff5",
   389  		"0x000000000ffffff0",
   390  		"0x0000000010000001",
   391  		0xff0000000fffffff,
   392  		"0x000000000bfffff4",
   393  		"0x0000000003400001",
   394  	},
   395  	{
   396  		"0x0000000080000000",
   397  		"0x00000000ffffffff",
   398  		"0x1000000000000001",
   399  		0xfffffffffffffff,
   400  		"0x0800000008000001",
   401  		"0x0800000008000001",
   402  	},
   403  	{
   404  		"0x0000000080000000",
   405  		"0x0000000080000000",
   406  		"0xffffffff00000001",
   407  		0xfffffffeffffffff,
   408  		"0xbfffffff40000001",
   409  		"0xbfffffff40000001",
   410  	},
   411  	{
   412  		"0x0000000080000000",
   413  		"0x0000000080000000",
   414  		"0x00ffffff00000001",
   415  		0xfffffeffffffff,
   416  		"0xbfffff40000001",
   417  		"0xbfffff40000001",
   418  	},
   419  	{
   420  		"0x0000000080000000",
   421  		"0x0000000080000000",
   422  		"0x0000ffff00000001",
   423  		0xfffeffffffff,
   424  		"0xbfff40000001",
   425  		"0xbfff40000001",
   426  	},
   427  	{
   428  		"0x3321ffffffffffffffffffffffffffff00000000000022222623333333332bbbb888c0",
   429  		"0x3321ffffffffffffffffffffffffffff00000000000022222623333333332bbbb888c0",
   430  		"0x33377fffffffffffffffffffffffffffffffffffffffffffff0000000000022222eee1",
   431  		0xdecc8f1249812adf,
   432  		"0x04eb0e11d72329dc0915f86784820fc403275bf2f6620a20e0dd344c5cd0875e50deb5",
   433  		"0x0d7144739a7d8e11d72329dc0915f86784820fc403275bf2f61ed96f35dd34dbb3d6a0",
   434  	},
   435  	{
   436  		"0x10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffff00000000000022222223333333333444444444",
   437  		"0x10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffff999999999999999aaabbbbbbbbcccccccccccc",
   438  		"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff33377fffffffffffffffffffffffffffffffffffffffffffff0000000000022222eee1",
   439  		0xdecc8f1249812adf,
   440  		"0x5c0d52f451aec609b15da8e5e5626c4eaa88723bdeac9d25ca9b961269400410ca208a16af9c2fb07d7a11c7772cba02c22f9711078d51a3797eb18e691295293284d988e349fa6deba46b25a4ecd9f715",
   441  		"0x92fcad4b5c0d52f451aec609b15da8e5e5626c4eaa88723bdeac9d25ca9b961269400410ca208a16af9c2fb07d799c32fe2f3cc5422f9711078d51a3797eb18e691295293284d8f5e69caf6decddfe1df6",
   442  	},
   443  }
   444  
   445  func TestMontgomery(t *testing.T) {
   446  	one := NewInt(1)
   447  	_B := new(Int).Lsh(one, _W)
   448  	for i, test := range montgomeryTests {
   449  		x := natFromString(test.x)
   450  		y := natFromString(test.y)
   451  		m := natFromString(test.m)
   452  		for len(x) < len(m) {
   453  			x = append(x, 0)
   454  		}
   455  		for len(y) < len(m) {
   456  			y = append(y, 0)
   457  		}
   458  
   459  		if x.cmp(m) > 0 {
   460  			_, r := nat(nil).div(nil, x, m)
   461  			t.Errorf("#%d: x > m (0x%s > 0x%s; use 0x%s)", i, x.utoa(16), m.utoa(16), r.utoa(16))
   462  		}
   463  		if y.cmp(m) > 0 {
   464  			_, r := nat(nil).div(nil, x, m)
   465  			t.Errorf("#%d: y > m (0x%s > 0x%s; use 0x%s)", i, y.utoa(16), m.utoa(16), r.utoa(16))
   466  		}
   467  
   468  		var out nat
   469  		if _W == 32 {
   470  			out = natFromString(test.out32)
   471  		} else {
   472  			out = natFromString(test.out64)
   473  		}
   474  
   475  		// t.Logf("#%d: len=%d\n", i, len(m))
   476  
   477  		// check output in table
   478  		xi := &Int{abs: x}
   479  		yi := &Int{abs: y}
   480  		mi := &Int{abs: m}
   481  		p := new(Int).Mod(new(Int).Mul(xi, new(Int).Mul(yi, new(Int).ModInverse(new(Int).Lsh(one, uint(len(m))*_W), mi))), mi)
   482  		if out.cmp(p.abs.norm()) != 0 {
   483  			t.Errorf("#%d: out in table=0x%s, computed=0x%s", i, out.utoa(16), p.abs.norm().utoa(16))
   484  		}
   485  
   486  		// check k0 in table
   487  		k := new(Int).Mod(&Int{abs: m}, _B)
   488  		k = new(Int).Sub(_B, k)
   489  		k = new(Int).Mod(k, _B)
   490  		k0 := Word(new(Int).ModInverse(k, _B).Uint64())
   491  		if k0 != Word(test.k0) {
   492  			t.Errorf("#%d: k0 in table=%#x, computed=%#x\n", i, test.k0, k0)
   493  		}
   494  
   495  		// check montgomery with correct k0 produces correct output
   496  		z := nat(nil).montgomery(x, y, m, k0, len(m))
   497  		z = z.norm()
   498  		if z.cmp(out) != 0 {
   499  			t.Errorf("#%d: got 0x%s want 0x%s", i, z.utoa(16), out.utoa(16))
   500  		}
   501  	}
   502  }
   503  
   504  var expNNTests = []struct {
   505  	x, y, m string
   506  	out     string
   507  }{
   508  	{"0", "0", "0", "1"},
   509  	{"0", "0", "1", "0"},
   510  	{"1", "1", "1", "0"},
   511  	{"2", "1", "1", "0"},
   512  	{"2", "2", "1", "0"},
   513  	{"10", "100000000000", "1", "0"},
   514  	{"0x8000000000000000", "2", "", "0x40000000000000000000000000000000"},
   515  	{"0x8000000000000000", "2", "6719", "4944"},
   516  	{"0x8000000000000000", "3", "6719", "5447"},
   517  	{"0x8000000000000000", "1000", "6719", "1603"},
   518  	{"0x8000000000000000", "1000000", "6719", "3199"},
   519  	{
   520  		"2938462938472983472983659726349017249287491026512746239764525612965293865296239471239874193284792387498274256129746192347",
   521  		"298472983472983471903246121093472394872319615612417471234712061",
   522  		"29834729834729834729347290846729561262544958723956495615629569234729836259263598127342374289365912465901365498236492183464",
   523  		"23537740700184054162508175125554701713153216681790245129157191391322321508055833908509185839069455749219131480588829346291",
   524  	},
   525  	{
   526  		"11521922904531591643048817447554701904414021819823889996244743037378330903763518501116638828335352811871131385129455853417360623007349090150042001944696604737499160174391019030572483602867266711107136838523916077674888297896995042968746762200926853379",
   527  		"426343618817810911523",
   528  		"444747819283133684179",
   529  		"42",
   530  	},
   531  	{"375", "249", "388", "175"},
   532  	{"375", "18446744073709551801", "388", "175"},
   533  	{"0", "0x40000000000000", "0x200", "0"},
   534  	{"0xeffffff900002f00", "0x40000000000000", "0x200", "0"},
   535  	{"5", "1435700818", "72", "49"},
   536  	{"0xffff", "0x300030003000300030003000300030003000302a3000300030003000300030003000300030003000300030003000300030003030623066307f3030783062303430383064303630343036", "0x300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "0xa3f94c08b0b90e87af637cacc9383f7ea032352b8961fc036a52b659b6c9b33491b335ffd74c927f64ddd62cfca0001"},
   537  }
   538  
   539  func TestExpNN(t *testing.T) {
   540  	for i, test := range expNNTests {
   541  		x := natFromString(test.x)
   542  		y := natFromString(test.y)
   543  		out := natFromString(test.out)
   544  
   545  		var m nat
   546  		if len(test.m) > 0 {
   547  			m = natFromString(test.m)
   548  		}
   549  
   550  		z := nat(nil).expNN(x, y, m, false)
   551  		if z.cmp(out) != 0 {
   552  			t.Errorf("#%d got %s want %s", i, z.utoa(10), out.utoa(10))
   553  		}
   554  	}
   555  }
   556  
   557  func FuzzExpMont(f *testing.F) {
   558  	f.Fuzz(func(t *testing.T, x1, x2, x3, y1, y2, y3, m1, m2, m3 uint) {
   559  		if m1 == 0 && m2 == 0 && m3 == 0 {
   560  			return
   561  		}
   562  		x := new(Int).SetBits([]Word{Word(x1), Word(x2), Word(x3)})
   563  		y := new(Int).SetBits([]Word{Word(y1), Word(y2), Word(y3)})
   564  		m := new(Int).SetBits([]Word{Word(m1), Word(m2), Word(m3)})
   565  		out := new(Int).Exp(x, y, m)
   566  		want := new(Int).expSlow(x, y, m)
   567  		if out.Cmp(want) != 0 {
   568  			t.Errorf("x = %#x\ny=%#x\nz=%#x\nout=%#x\nwant=%#x\ndc: 16o 16i %X %X %X |p", x, y, m, out, want, x, y, m)
   569  		}
   570  	})
   571  }
   572  
   573  func BenchmarkExp3Power(b *testing.B) {
   574  	const x = 3
   575  	for _, y := range []Word{
   576  		0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000,
   577  	} {
   578  		b.Run(fmt.Sprintf("%#x", y), func(b *testing.B) {
   579  			var z nat
   580  			for i := 0; i < b.N; i++ {
   581  				z.expWW(x, y)
   582  			}
   583  		})
   584  	}
   585  }
   586  
   587  func fibo(n int) nat {
   588  	switch n {
   589  	case 0:
   590  		return nil
   591  	case 1:
   592  		return nat{1}
   593  	}
   594  	f0 := fibo(0)
   595  	f1 := fibo(1)
   596  	var f2 nat
   597  	for i := 1; i < n; i++ {
   598  		f2 = f2.add(f0, f1)
   599  		f0, f1, f2 = f1, f2, f0
   600  	}
   601  	return f1
   602  }
   603  
   604  var fiboNums = []string{
   605  	"0",
   606  	"55",
   607  	"6765",
   608  	"832040",
   609  	"102334155",
   610  	"12586269025",
   611  	"1548008755920",
   612  	"190392490709135",
   613  	"23416728348467685",
   614  	"2880067194370816120",
   615  	"354224848179261915075",
   616  }
   617  
   618  func TestFibo(t *testing.T) {
   619  	for i, want := range fiboNums {
   620  		n := i * 10
   621  		got := string(fibo(n).utoa(10))
   622  		if got != want {
   623  			t.Errorf("fibo(%d) failed: got %s want %s", n, got, want)
   624  		}
   625  	}
   626  }
   627  
   628  func BenchmarkFibo(b *testing.B) {
   629  	for i := 0; i < b.N; i++ {
   630  		fibo(1e0)
   631  		fibo(1e1)
   632  		fibo(1e2)
   633  		fibo(1e3)
   634  		fibo(1e4)
   635  		fibo(1e5)
   636  	}
   637  }
   638  
   639  var bitTests = []struct {
   640  	x    string
   641  	i    uint
   642  	want uint
   643  }{
   644  	{"0", 0, 0},
   645  	{"0", 1, 0},
   646  	{"0", 1000, 0},
   647  
   648  	{"0x1", 0, 1},
   649  	{"0x10", 0, 0},
   650  	{"0x10", 3, 0},
   651  	{"0x10", 4, 1},
   652  	{"0x10", 5, 0},
   653  
   654  	{"0x8000000000000000", 62, 0},
   655  	{"0x8000000000000000", 63, 1},
   656  	{"0x8000000000000000", 64, 0},
   657  
   658  	{"0x3" + strings.Repeat("0", 32), 127, 0},
   659  	{"0x3" + strings.Repeat("0", 32), 128, 1},
   660  	{"0x3" + strings.Repeat("0", 32), 129, 1},
   661  	{"0x3" + strings.Repeat("0", 32), 130, 0},
   662  }
   663  
   664  func TestBit(t *testing.T) {
   665  	for i, test := range bitTests {
   666  		x := natFromString(test.x)
   667  		if got := x.bit(test.i); got != test.want {
   668  			t.Errorf("#%d: %s.bit(%d) = %v; want %v", i, test.x, test.i, got, test.want)
   669  		}
   670  	}
   671  }
   672  
   673  var stickyTests = []struct {
   674  	x    string
   675  	i    uint
   676  	want uint
   677  }{
   678  	{"0", 0, 0},
   679  	{"0", 1, 0},
   680  	{"0", 1000, 0},
   681  
   682  	{"0x1", 0, 0},
   683  	{"0x1", 1, 1},
   684  
   685  	{"0x1350", 0, 0},
   686  	{"0x1350", 4, 0},
   687  	{"0x1350", 5, 1},
   688  
   689  	{"0x8000000000000000", 63, 0},
   690  	{"0x8000000000000000", 64, 1},
   691  
   692  	{"0x1" + strings.Repeat("0", 100), 400, 0},
   693  	{"0x1" + strings.Repeat("0", 100), 401, 1},
   694  }
   695  
   696  func TestSticky(t *testing.T) {
   697  	for i, test := range stickyTests {
   698  		x := natFromString(test.x)
   699  		if got := x.sticky(test.i); got != test.want {
   700  			t.Errorf("#%d: %s.sticky(%d) = %v; want %v", i, test.x, test.i, got, test.want)
   701  		}
   702  		if test.want == 1 {
   703  			// all subsequent i's should also return 1
   704  			for d := uint(1); d <= 3; d++ {
   705  				if got := x.sticky(test.i + d); got != 1 {
   706  					t.Errorf("#%d: %s.sticky(%d) = %v; want %v", i, test.x, test.i+d, got, 1)
   707  				}
   708  			}
   709  		}
   710  	}
   711  }
   712  
   713  func testSqr(t *testing.T, x nat) {
   714  	got := make(nat, 2*len(x))
   715  	want := make(nat, 2*len(x))
   716  	got = got.sqr(x)
   717  	want = want.mul(x, x)
   718  	if got.cmp(want) != 0 {
   719  		t.Errorf("basicSqr(%v), got %v, want %v", x, got, want)
   720  	}
   721  }
   722  
   723  func TestSqr(t *testing.T) {
   724  	for _, a := range prodNN {
   725  		if a.x != nil {
   726  			testSqr(t, a.x)
   727  		}
   728  		if a.y != nil {
   729  			testSqr(t, a.y)
   730  		}
   731  		if a.z != nil {
   732  			testSqr(t, a.z)
   733  		}
   734  	}
   735  }
   736  
   737  func benchmarkNatSqr(b *testing.B, nwords int) {
   738  	x := rndNat(nwords)
   739  	var z nat
   740  	b.ResetTimer()
   741  	for i := 0; i < b.N; i++ {
   742  		z.sqr(x)
   743  	}
   744  }
   745  
   746  var sqrBenchSizes = []int{
   747  	1, 2, 3, 5, 8, 10, 20, 30, 50, 80,
   748  	100, 200, 300, 500, 800,
   749  	1000, 10000, 100000,
   750  }
   751  
   752  func BenchmarkNatSqr(b *testing.B) {
   753  	for _, n := range sqrBenchSizes {
   754  		if isRaceBuilder && n > 1e3 {
   755  			continue
   756  		}
   757  		b.Run(fmt.Sprintf("%d", n), func(b *testing.B) {
   758  			benchmarkNatSqr(b, n)
   759  		})
   760  	}
   761  }
   762  
   763  var subMod2NTests = []struct {
   764  	x string
   765  	y string
   766  	n uint
   767  	z string
   768  }{
   769  	{"1", "2", 0, "0"},
   770  	{"1", "0", 1, "1"},
   771  	{"0", "1", 1, "1"},
   772  	{"3", "5", 3, "6"},
   773  	{"5", "3", 3, "2"},
   774  	// 2^65, 2^66-1, 2^65 - (2^66-1) + 2^67
   775  	{"36893488147419103232", "73786976294838206463", 67, "110680464442257309697"},
   776  	// 2^66-1, 2^65, 2^65-1
   777  	{"73786976294838206463", "36893488147419103232", 67, "36893488147419103231"},
   778  }
   779  
   780  func TestNatSubMod2N(t *testing.T) {
   781  	for _, mode := range []string{"noalias", "aliasX", "aliasY"} {
   782  		t.Run(mode, func(t *testing.T) {
   783  			for _, tt := range subMod2NTests {
   784  				x0 := natFromString(tt.x)
   785  				y0 := natFromString(tt.y)
   786  				want := natFromString(tt.z)
   787  				x := nat(nil).set(x0)
   788  				y := nat(nil).set(y0)
   789  				var z nat
   790  				switch mode {
   791  				case "aliasX":
   792  					z = x
   793  				case "aliasY":
   794  					z = y
   795  				}
   796  				z = z.subMod2N(x, y, tt.n)
   797  				if z.cmp(want) != 0 {
   798  					t.Fatalf("subMod2N(%d, %d, %d) = %d, want %d", x0, y0, tt.n, z, want)
   799  				}
   800  				if mode != "aliasX" && x.cmp(x0) != 0 {
   801  					t.Fatalf("subMod2N(%d, %d, %d) modified x", x0, y0, tt.n)
   802  				}
   803  				if mode != "aliasY" && y.cmp(y0) != 0 {
   804  					t.Fatalf("subMod2N(%d, %d, %d) modified y", x0, y0, tt.n)
   805  				}
   806  			}
   807  		})
   808  	}
   809  }
   810  
   811  func BenchmarkNatSetBytes(b *testing.B) {
   812  	const maxLength = 128
   813  	lengths := []int{
   814  		// No remainder:
   815  		8, 24, maxLength,
   816  		// With remainder:
   817  		7, 23, maxLength - 1,
   818  	}
   819  	n := make(nat, maxLength/_W) // ensure n doesn't need to grow during the test
   820  	buf := make([]byte, maxLength)
   821  	for _, l := range lengths {
   822  		b.Run(fmt.Sprint(l), func(b *testing.B) {
   823  			for i := 0; i < b.N; i++ {
   824  				n.setBytes(buf[:l])
   825  			}
   826  		})
   827  	}
   828  }
   829  
   830  func TestNatDiv(t *testing.T) {
   831  	sizes := []int{
   832  		1, 2, 5, 8, 15, 25, 40, 65, 100,
   833  		200, 500, 800, 1500, 2500, 4000, 6500, 10000,
   834  	}
   835  	for _, i := range sizes {
   836  		for _, j := range sizes {
   837  			a := rndNat1(i)
   838  			b := rndNat1(j)
   839  			// the test requires b >= 2
   840  			if len(b) == 1 && b[0] == 1 {
   841  				b[0] = 2
   842  			}
   843  			// choose a remainder c < b
   844  			c := rndNat1(len(b))
   845  			if len(c) == len(b) && c[len(c)-1] >= b[len(b)-1] {
   846  				c[len(c)-1] = 0
   847  				c = c.norm()
   848  			}
   849  			// compute x = a*b+c
   850  			x := nat(nil).mul(a, b)
   851  			x = x.add(x, c)
   852  
   853  			var q, r nat
   854  			q, r = q.div(r, x, b)
   855  			if q.cmp(a) != 0 {
   856  				t.Fatalf("wrong quotient: got %s; want %s for %s/%s", q.utoa(10), a.utoa(10), x.utoa(10), b.utoa(10))
   857  			}
   858  			if r.cmp(c) != 0 {
   859  				t.Fatalf("wrong remainder: got %s; want %s for %s/%s", r.utoa(10), c.utoa(10), x.utoa(10), b.utoa(10))
   860  			}
   861  		}
   862  	}
   863  }
   864  
   865  // TestIssue37499 triggers the edge case of divBasic where
   866  // the inaccurate estimate of the first word's quotient
   867  // happens at the very beginning of the loop.
   868  func TestIssue37499(t *testing.T) {
   869  	// Choose u and v such that v is slightly larger than u >> N.
   870  	// This tricks divBasic into choosing 1 as the first word
   871  	// of the quotient. This works in both 32-bit and 64-bit settings.
   872  	u := natFromString("0x2b6c385a05be027f5c22005b63c42a1165b79ff510e1706b39f8489c1d28e57bb5ba4ef9fd9387a3e344402c0a453381")
   873  	v := natFromString("0x2b6c385a05be027f5c22005b63c42a1165b79ff510e1706c")
   874  
   875  	q := nat(nil).make(8)
   876  	q.divBasic(u, v)
   877  	q = q.norm()
   878  	if s := string(q.utoa(16)); s != "fffffffffffffffffffffffffffffffffffffffffffffffb" {
   879  		t.Fatalf("incorrect quotient: %s", s)
   880  	}
   881  }
   882  
   883  // TestIssue42552 triggers an edge case of recursive division
   884  // where the first division loop is never entered, and correcting
   885  // the remainder takes exactly two iterations in the final loop.
   886  func TestIssue42552(t *testing.T) {
   887  	u := natFromString("0xc23b166884c3869092a520eceedeced2b00847bd256c9cf3b2c5e2227c15bd5e6ee7ef8a2f49236ad0eedf2c8a3b453cf6e0706f64285c526b372c4b1321245519d430540804a50b7ca8b6f1b34a2ec05cdbc24de7599af112d3e3c8db347e8799fe70f16e43c6566ba3aeb169463a3ecc486172deb2d9b80a3699c776e44fef20036bd946f1b4d054dd88a2c1aeb986199b0b2b7e58c42288824b74934d112fe1fc06e06b4d99fe1c5e725946b23210521e209cd507cce90b5f39a523f27e861f9e232aee50c3f585208b4573dcc0b897b6177f2ba20254fd5c50a033e849dee1b3a93bd2dc44ba8ca836cab2c2ae50e50b126284524fa0187af28628ff0face68d87709200329db1392852c8b8963fbe3d05fb1efe19f0ed5ca9fadc2f96f82187c24bb2512b2e85a66333a7e176605695211e1c8e0b9b9e82813e50654964945b1e1e66a90840396c7d10e23e47f364d2d3f660fa54598e18d1ca2ea4fe4f35a40a11f69f201c80b48eaee3e2e9b0eda63decf92bec08a70f731587d4ed0f218d5929285c8b2ccbc497e20db42de73885191fa453350335990184d8df805072f958d5354debda38f5421effaaafd6cb9b721ace74be0892d77679f62a4a126697cd35797f6858193da4ba1770c06aea2e5c59ec04b8ea26749e61b72ecdde403f3bc7e5e546cd799578cc939fa676dfd5e648576d4a06cbadb028adc2c0b461f145b2321f42e5e0f3b4fb898ecd461df07a6f5154067787bf74b5cc5c03704a1ce47494961931f0263b0aac32505102595957531a2de69dd71aac51f8a49902f81f21283dbe8e21e01e5d82517868826f86acf338d935aa6b4d5a25c8d540389b277dd9d64569d68baf0f71bd03dba45b92a7fc052601d1bd011a2fc6790a23f97c6fa5caeea040ab86841f268d39ce4f7caf01069df78bba098e04366492f0c2ac24f1bf16828752765fa523c9a4d42b71109d123e6be8c7b1ab3ccf8ea03404075fe1a9596f1bba1d267f9a7879ceece514818316c9c0583469d2367831fc42b517ea028a28df7c18d783d16ea2436cee2b15d52db68b5dfdee6b4d26f0905f9b030c911a04d078923a4136afea96eed6874462a482917353264cc9bee298f167ac65a6db4e4eda88044b39cc0b33183843eaa946564a00c3a0ab661f2c915e70bf0bb65bfbb6fa2eea20aed16bf2c1a1d00ec55fb4ff2f76b8e462ea70c19efa579c9ee78194b86708fdae66a9ce6e2cf3d366037798cfb50277ba6d2fd4866361022fd788ab7735b40b8b61d55e32243e06719e53992e9ac16c9c4b6e6933635c3c47c8f7e73e17dd54d0dd8aeba5d76de46894e7b3f9d3ec25ad78ee82297ba69905ea0fa094b8667faa2b8885e2187b3da80268aa1164761d7b0d6de206b676777348152b8ae1d4afed753bc63c739a5ca8ce7afb2b241a226bd9e502baba391b5b13f5054f070b65a9cf3a67063bfaa803ba390732cd03888f664023f888741d04d564e0b5674b0a183ace81452001b3fbb4214c77d42ca75376742c471e58f67307726d56a1032bd236610cbcbcd03d0d7a452900136897dc55bb3ce959d10d4e6a10fb635006bd8c41cd9ded2d3dfdd8f2e229590324a7370cb2124210b2330f4c56155caa09a2564932ceded8d92c79664dcdeb87faad7d3da006cc2ea267ee3df41e9677789cc5a8cc3b83add6491561b3047919e0648b1b2e97d7ad6f6c2aa80cab8e9ae10e1f75b1fdd0246151af709d259a6a0ed0b26bd711024965ecad7c41387de45443defce53f66612948694a6032279131c257119ed876a8e805dfb49576ef5c563574115ee87050d92d191bc761ef51d966918e2ef925639400069e3959d8fe19f36136e947ff430bf74e71da0aa5923b00000000")
   888  	v := natFromString("0x838332321d443a3d30373d47301d47073847473a383d3030f25b3d3d3e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002e00000000000000000041603038331c3d32f5303441e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e01c0a5459bfc7b9be9fcbb9d2383840464319434707303030f43a32f53034411c0a5459413820878787878787878787878787878787878787878787878787878787878787878787870630303a3a30334036605b923a6101f83638413943413960204337602043323801526040523241846038414143015238604060328452413841413638523c0240384141364036605b923a6101f83638413943413960204334602043323801526040523241846038414143015238604060328452413841413638523c02403841413638433030f25a8b83838383838383838383838383838383837d838383ffffffffffffffff838383838383838383000000000000000000030000007d26e27c7c8b83838383838383838383838383838383837d838383ffffffffffffffff83838383838383838383838383838383838383838383435960f535073030f3343200000000000000011881301938343030fa398383300000002300000000000000000000f11af4600c845252904141364138383c60406032414443095238010241414303364443434132305b595a15434160b042385341ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff47476043410536613603593a6005411c437405fcfcfcfcfcfcfc0000000000005a3b075815054359000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
   889  	q := nat(nil).make(16)
   890  	q.div(q, u, v)
   891  }
   892  

View as plain text