Find the inverse of BigInt @x in a field of (prime) order @p.
187307
def inverse(x, p, errorOnFail=False):
    
    # Check types
    assertType(x, BigInt)

    # There are a number of ways in RELIC to compute this inverse, but
    # for simplicity, we'll use the extended GCD algorithm because it 
    # involves less type conversions. On the initial development platform
    # Lehmer's algorithm was the most performant: we call it directly.
    gcd = BigInt()
    inv = BigInt()

    # bn_gcd_ext(c, d, e, a, b) computes: c = a*d + b*e
    # We take x=a. b=p, and expect: c = 1 = gcd(x,p), d = 1/x, and e is unused.
    librelic.bn_gcd_ext_lehme(byref(gcd), byref(inv), None, byref(x), byref(p))

    # Check that GCD == 1 
    if gcd != 1:
        if errorOnFail:
            raise Exception("Cannot find an inverse. gcd(x,p) == {}, but we need gcd(x,p) == 1 to find an inverse.".
                format(long(gcd)))
        else:
            return None

    return inv
1051464
def get_prime(bits, k=64):
    
    if bits % 8 != 0 or bits == 0:
        raise ValueError("bits must be >= 0 and divisible by 8")
    while True:
        n = int.from_bytes(os.urandom(bits // 8), "big")
        if is_prime(n, k):
            return n
53595
int findPrimary(long p) {
        // Requirement: p must occur as a root primary.
        assert((p & 0xff) == 0);  // at most a 3-byte primary
        int index = findP(p);
        // If p is in a range, then we just assume that p is an actual primary in this range.
        // (Too cumbersome/expensive to check.)
        // Otherwise, it must be an exact match.
        assert(isEndOfPrimaryRange(elements[index + 1]) || p == (elements[index] & 0xffffff00L));
        return index;
    }
434265
public function inverse($p)
    {
        $p->x -= $this->x0;
        $p->y = $this->rh - $p->y + $this->y0;

        if ($this->ns >= 0) {
            $rh1 = sqrt( $p->x * $p->x + $p->y * $p->y );
            $con = 1.0;
        } else {
            $rh1 = -sqrt( $p->x * $p->x + $p->y * $p->y );
            $con = -1.0;
        }

        $theta = 0.0;

        if ($rh1 != 0.0) {
            $theta = atan2($con * $p->x, $con * $p->y);
        }

        $ml = $this->g - $rh1 / $this->a;

        $lat = $this->phi3z( $ml, $this->e0, $this->e1, $this->e2, $this->e3 );
        $lon = Common::adjust_lon( $this->long0 + $theta / $this->ns );

        $p->x = $lon;
        $p->y = $lat;

        return $p;
    }
92161
public static BigDecimal inverse(final BigDecimal value, final int scale, final int rounding) {
        if (isNotZero(value)) {
            return BigDecimal.ONE.divide(value, scale, rounding);
        }
        return null;
    }
1063281
public function inverse( $p ) {
        
        $p->x -= $this->x0;
        $p->y -= $this->y0;

        $lon = Common::adjust_lon( $this->long0 + $p->x / $this->a );
        $lat = 2.5 * (atan( exp( 0.8 * $p->y / $this->a ) ) - Common::PI / 4.0);

        $p->x = $lon;
        $p->y = $lat;
        
        return $p;
    }
1301593
public static BigInteger modInverse(BigInteger val, BigInteger modulus) {
    if (modulus.signum() <= 0) {
      throw new ArithmeticException("modulus must be positive");
    }
    return INSTANCE.get().modInverseImpl(val, modulus);
  }
324352
function inverseMod_(x, n) {
  var k=1+2*Math.max(x.length, n.length);

  if (!(x[0]&1)  && !(n[0]&1)) {  //if both inputs are even, then inverse doesn't exist
    copyInt_(x, 0);
    return 0;
  }

  if (eg_u.length!=k) {
    eg_u=new Array(k);
    eg_v=new Array(k);
    eg_A=new Array(k);
    eg_B=new Array(k);
    eg_C=new Array(k);
    eg_D=new Array(k);
  }

  copy_(eg_u, x);
  copy_(eg_v, n);
  copyInt_(eg_A, 1);
  copyInt_(eg_B, 0);
  copyInt_(eg_C, 0);
  copyInt_(eg_D, 1);
  for (;;) {
    while (!(eg_u[0]&1)) {  //while eg_u is even
      halve_(eg_u);
      if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if eg_A==eg_B==0 mod 2
        halve_(eg_A);
        halve_(eg_B);
      } else {
        add_(eg_A, n);  halve_(eg_A);
        sub_(eg_B, x);  halve_(eg_B);
      }
    }

    while (!(eg_v[0]&1)) {  //while eg_v is even
      halve_(eg_v);
      if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if eg_C==eg_D==0 mod 2
        halve_(eg_C);
        halve_(eg_D);
      } else {
        add_(eg_C, n);  halve_(eg_C);
        sub_(eg_D, x);  halve_(eg_D);
      }
    }

    if (!greater(eg_v, eg_u)) { //eg_v <= eg_u
      sub_(eg_u, eg_v);
      sub_(eg_A, eg_C);
      sub_(eg_B, eg_D);
    } else {                   //eg_v > eg_u
      sub_(eg_v, eg_u);
      sub_(eg_C, eg_A);
      sub_(eg_D, eg_B);
    }

    if (equalsInt(eg_u, 0)) {
      while (negative(eg_C)) //make sure answer is nonnegative
        add_(eg_C, n);
      copy_(x, eg_C);

      if (!equalsInt(eg_v, 1)) { //if GCD_(x,n)!=1, then there is no inverse
        copyInt_(x, 0);
        return 0;
      }
      return 1;
    }
  }
}
829809
def generate_key(k, seed=None):
    

    def modinv(a, m):
        """calculate the inverse of a mod m
        that is, find b such that (a * b) % m == 1"""
        b = 1
        while not (a * b) % m == 1:
            b += 1
        return b

    def gen_prime(k, seed=None):
        """generate a prime with k bits"""

        def is_prime(num):
            if num == 2:
                return True
            for i in range(2, int(num ** 0.5) + 1):
                if num % i == 0:
                    return False
            return True

        random.seed(seed)
        while True:
            key = random.randrange(int(2 ** (k - 1)), int(2 ** k))
            if is_prime(key):
                return key

    # size in bits of p and q need to add up to the size of n
    p_size = k / 2
    q_size = k - p_size
    
    e = gen_prime(k, seed)  # in many cases, e is also chosen to be a small constant
    
    while True:
        p = gen_prime(p_size, seed)
        if p % e != 1:
            break
    
    while True:
        q = gen_prime(q_size, seed)
        if q % e != 1:
            break
    
    n = p * q
    l = (p - 1) * (q - 1)  # calculate totient function
    d = modinv(e, l)
    
    return int(n), int(e), int(d)
1362767
function bitwise_and($x)
    {
        switch (MATH_BIGINTEGER_MODE) {
            case self::MODE_GMP:
                $temp = new static();
                $temp->value = gmp_and($this->value, $x->value);

                return $this->_normalize($temp);
            case self::MODE_BCMATH:
                $left = $this->toBytes();
                $right = $x->toBytes();

                $length = max(strlen($left), strlen($right));

                $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
                $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);

                return $this->_normalize(new static($left & $right, 256));
        }

        $result = $this->copy();

        $length = min(count($x->value), count($this->value));

        $result->value = array_slice($result->value, 0, $length);

        for ($i = 0; $i < $length; ++$i) {
            $result->value[$i]&= $x->value[$i];
        }

        return $this->_normalize($result);
    }
1113135
def int2baseTwo(x):
    """"""
    # repeating x >>= 1 and x & 1 will do the trick
    assert x >= 0
    bitInverse = []
    while x != 0:
        bitInverse.append(x & 1)
        x >>= 1
    return bitInverse
865784
def p_xor_p_expression(tok):
        """"""
        if len(tok) == 4:
            tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
        else:
            tok[0] = tok[1]
997652
private BigInteger bigMultiplyPowerTen(int n) {
        if (n <= 0)
            return this.inflated();

        if (intCompact != INFLATED)
            return bigTenToThe(n).multiply(intCompact);
        else
            return intVal.multiply(bigTenToThe(n));
    }
959501
def _findNextPrime(self, N):
        """"""
        primes = self.primes
        nextPrime = primes[-1]+1
        while(len(primes)<N):
            maximum = nextPrime * nextPrime
            prime = 1
            for i in primes:
                if i > maximum:
                    break
                if nextPrime % i == 0:
                    prime = 0
                    break
            if prime:
                primes.append(nextPrime)
            nextPrime+=1
996232
function equals($x)
    {
        switch (MATH_BIGINTEGER_MODE) {
            case MATH_BIGINTEGER_MODE_GMP:
                return gmp_cmp($this->value, $x->value) == 0;
            default:
                return $this->value === $x->value && $this->is_negative == $x->is_negative;
        }
    }
1167355
function bitwise_xor($x)
    {
        switch (MATH_BIGINTEGER_MODE) {
            case self::MODE_GMP:
                $temp = new static();
                $temp->value = gmp_xor(gmp_abs($this->value), gmp_abs($x->value));
                return $this->_normalize($temp);
            case self::MODE_BCMATH:
                $left = $this->toBytes();
                $right = $x->toBytes();

                $length = max(strlen($left), strlen($right));

                $left = str_pad($left, $length, chr(0), STR_PAD_LEFT);
                $right = str_pad($right, $length, chr(0), STR_PAD_LEFT);

                return $this->_normalize(new static($left ^ $right, 256));
        }

        $length = max(count($this->value), count($x->value));
        $result = $this->copy();
        $result->is_negative = false;
        $result->value = array_pad($result->value, $length, 0);
        $x->value = array_pad($x->value, $length, 0);

        for ($i = 0; $i < $length; ++$i) {
            $result->value[$i]^= $x->value[$i];
        }

        return $this->_normalize($result);
    }
1243387
function inverse$11(p) {
        p.x -= this.x0;
        p.y -= this.y0;
        var x = p.x / this.a;
        var y = p.y / this.a;
        var phi, lam;

        if (this.sphere) {
            var dd = y + this.lat0;
            phi = Math.asin(Math.sin(dd) * Math.cos(x));
            lam = Math.atan2(Math.tan(x), Math.cos(dd));
        }
        else {
            /* ellipsoid */
            var ml1 = this.ml0 / this.a + y;
            var phi1 = imlfn(ml1, this.e0, this.e1, this.e2, this.e3);
            if (Math.abs(Math.abs(phi1) - HALF_PI) <= EPSLN) {
                p.x = this.long0;
                p.y = HALF_PI;
                if (y < 0) {
                    p.y *= -1;
                }
                return p;
            }
            var nl1 = gN(this.a, this.e, Math.sin(phi1));

            var rl1 = nl1 * nl1 * nl1 / this.a / this.a * (1 - this.es);
            var tl1 = Math.pow(Math.tan(phi1), 2);
            var dl = x * this.a / nl1;
            var dsq = dl * dl;
            phi = phi1 - nl1 * Math.tan(phi1) / rl1 * dl * dl * (0.5 - (1 + 3 * tl1) * dl * dl / 24);
            lam = dl * (1 - dsq * (tl1 / 3 + (1 + 3 * tl1) * tl1 * dsq / 15)) / Math.cos(phi1);

        }

        p.x = adjust_lon(lam + this.long0);
        p.y = adjust_lat(phi);
        return p;

    }