@Override
    public Polynomial invert(Polynomial polynomial, Polynomial moduloPolynomial) {

        if (isZero(polynomial) || isZero(moduloPolynomial)) {
            throw new MathIllegalArgumentException("Cannot compute inverse for zero polynomials.");
        }

        if ((polynomial.getSize() >= moduloPolynomial.getSize()) || (moduloPolynomial.getSize() == 1)) {
            throw new MathArithmeticException("Cannot compute inverse for this args.");
        }

        if (polynomial.getSize() == 1) {
            //special solution for special case 
            return divide(add(new Polynomial(1, 1), multiply(moduloPolynomial, polynomial)), polynomial);
        }

        Polynomial gcd;
        Polynomial result = new Polynomial(moduloPolynomial.getSize());
        Polynomial temp = new Polynomial(moduloPolynomial.getSize());

        //xgcd to set the result
        gcd = xgcd(moduloPolynomial, polynomial, temp, result);

        if (gcd.getSize() != 1) {
            throw new MathArithmeticException("Cannot compute inverse for this args.");
        }

        //normalize result, after this, remainder after division by moduloPolynomial will be 1
        result.clearZeroValues();
        return divide(result, gcd);
    }