github.com/emmansun/gmsm@v0.29.1/internal/sm2ec/fiat/sm2p256_invert.go (about)

     1  // Copyright 2021 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  // Code generated by addchain. DO NOT EDIT.
     5  package fiat
     6  
     7  // Invert sets e = 1/x, and returns e.
     8  //
     9  // If x == 0, Invert returns e = 0.
    10  func (e *SM2P256Element) Invert(x *SM2P256Element) *SM2P256Element {
    11  	// Inversion is implemented as exponentiation with exponent p − 2.
    12  	// The sequence of 14 multiplications and 255 squarings is derived from the
    13  	// following addition chain generated with github.com/mmcloughlin/addchain v0.4.0.
    14  	//
    15  	//	_10      = 2*1
    16  	//	_11      = 1 + _10
    17  	//	_110     = 2*_11
    18  	//	_111     = 1 + _110
    19  	//	_111000  = _111 << 3
    20  	//	_111111  = _111 + _111000
    21  	//	_1111110 = 2*_111111
    22  	//	_1111111 = 1 + _1111110
    23  	//	x12      = _1111110 << 5 + _111111
    24  	//	x24      = x12 << 12 + x12
    25  	//	x31      = x24 << 7 + _1111111
    26  	//	i39      = x31 << 2
    27  	//	i68      = i39 << 29
    28  	//	x62      = x31 + i68
    29  	//	i71      = i68 << 2
    30  	//	x64      = i39 + i71 + _11
    31  	//	i265     = ((i71 << 32 + x64) << 64 + x64) << 94
    32  	//	return     (x62 + i265) << 2 + 1
    33  	//
    34  	var z = new(SM2P256Element).Set(e)
    35  	var t0 = new(SM2P256Element)
    36  	var t1 = new(SM2P256Element)
    37  	var t2 = new(SM2P256Element)
    38  
    39  	z.Square(x)
    40  	t0.Mul(x, z)
    41  	z.Square(t0)
    42  	z.Mul(x, z)
    43  	t1.Square(z)
    44  	for s := 1; s < 3; s++ {
    45  		t1.Square(t1)
    46  	}
    47  	t1.Mul(z, t1)
    48  	t2.Square(t1)
    49  	z.Mul(x, t2)
    50  	for s := 0; s < 5; s++ {
    51  		t2.Square(t2)
    52  	}
    53  	t1.Mul(t1, t2)
    54  	t2.Square(t1)
    55  	for s := 1; s < 12; s++ {
    56  		t2.Square(t2)
    57  	}
    58  	t1.Mul(t1, t2)
    59  	for s := 0; s < 7; s++ {
    60  		t1.Square(t1)
    61  	}
    62  	z.Mul(z, t1)
    63  	t2.Square(z)
    64  	for s := 1; s < 2; s++ {
    65  		t2.Square(t2)
    66  	}
    67  	t1.Square(t2)
    68  	for s := 1; s < 29; s++ {
    69  		t1.Square(t1)
    70  	}
    71  	z.Mul(z, t1)
    72  	for s := 0; s < 2; s++ {
    73  		t1.Square(t1)
    74  	}
    75  	t2.Mul(t2, t1)
    76  	t0.Mul(t0, t2)
    77  	for s := 0; s < 32; s++ {
    78  		t1.Square(t1)
    79  	}
    80  	t1.Mul(t0, t1)
    81  	for s := 0; s < 64; s++ {
    82  		t1.Square(t1)
    83  	}
    84  	t0.Mul(t0, t1)
    85  	for s := 0; s < 94; s++ {
    86  		t0.Square(t0)
    87  	}
    88  	z.Mul(z, t0)
    89  	for s := 0; s < 2; s++ {
    90  		z.Square(z)
    91  	}
    92  	z.Mul(x, z)
    93  	return e.Set(z)
    94  }