1

I want to ask Matlab to tell me, for example, the greatest common divisor of polynomials of x^4+x^3+2x+2 and x^3+x^2+x+1 over fields like Z_3[x] (where an answer is x+1) and Z_5[x] (where an answer is x^2-x+2).

Any ideas how I would implement this?

Maths student
  • 143
  • 1
  • 1
  • 5
  • Are you looking to actually implement an algorithm yourself or can you use an existing implementation like this? http://www.mathworks.com/help/symbolic/mupad_ref/gcd.html – eigenchris Mar 16 '15 at 19:42
  • @eigenchris it says you can't use that in matlab? I'm not looking to implement my own algorithm, I simply want something to calculate it for me. (I tried wolfram alpha, but every single answer is coming out as 1!) – Maths student Mar 16 '15 at 19:54
  • (Actually user error might be the reason it is coming out as 1, but I would still like a way to calculate this using matlab) – Maths student Mar 16 '15 at 20:06
  • Shouldn't be that difficult: http://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor#Univariate_polynomials_with_coefficients_in_a_field – knedlsepp Mar 16 '15 at 20:55

1 Answers1

2

Here's a simple implementation. The polynomials are encoded as arrays of coefficients, starting from the lowest degree: so, x^4+x^3+2x+2 is [2 2 0 1 1]. The function takes two polynomials p, q and the modulus k (which should be prime for the algorithm to work property).

Examples:

  • gcdpolyff([2 2 0 1 1], [1 1 1 1], 3) returns [1 1] meaning 1+x.
  • gcdpolyff([2 2 0 1 1], [1 1 1 1], 5) returns [1 3 2] meaning 1+3x+2x^2; this disagrees with your answer but I hand-checked and it seems that yours is wrong.

The function first pads arrays to be of the same length. As long as they are not equal, is identifies the higher-degree polynomial and subtracts from it the lower-degree polynomial multiplied by an appropriate power of x. That's all.

function g = gcdpolyff(p, q, k)
p = [p, zeros(1, numel(q)-numel(p))];
q = [q, zeros(1, numel(p)-numel(q))];
while nnz(mod(p-q,k))>0
    dp = find(p,1,'last');
    dq = find(q,1,'last');
    if (dp>=dq)
        p(dp-dq+1:dp) = mod(p(1+dp-dq:dp) - q(1:dq), k);
    else
        q(dq-dp+1:dq) = mod(q(dq-dp+1:dq) - p(1:dp), k);
    end
end
g = p(1:find(p,1,'last'));
end

The names of the variables dp and dq are slightly misleading: they are not degrees of p and q, but rather degrees + 1.