Based on the code snippet here, I try to calculate the Rational Canonical Form of a square matrix as follows:
 
In[84]:= CompanionMatrix[p_, x_] := Module[
  {n, w = CoefficientList[p, x]},
  w = -w/Last[w];
  n = Length[w] - 1;
  SparseArray[{{i_, n} :> w[[i]], {i_, j_} /; i == j + 1 -> 1}, {n, 
    n}]]
MatrixMinimalPolynomial[a_List?MatrixQ, x_] := 
 Module[{i, n = 1, qu = {}, 
   mnm = {Flatten[IdentityMatrix[Length[a]]]}}, 
  While[Length[qu] == 0, AppendTo[mnm, Flatten[MatrixPower[a, n]]];
   qu = NullSpace[Transpose[mnm]];
   n++];
  First[qu] . Table[x^i, {i, 0, n - 1}]]
rationalMatrixForm[a_?(MatrixQ[#, NumericQ] &)] := Module[(*version 8/24/13 2PM*)
  {p, q, min, c = {}, moreFactors = True, z, x},
  p = CharacteristicPolynomial[a, x];
  min = MatrixMinimalPolynomial[a, x];
  While[moreFactors,
   q = PolynomialQuotient[p, min, x];
   If[q === 0,
    moreFactors = False;
    If[Not[FreeQ[p, x]],
     z = CompanionMatrix[p, x];
     AppendTo[c, z]
     ],
    z = CompanionMatrix[min, x];
    AppendTo[c, z];
    p = q
    ] (* if *)
   ]; (*end WHILE more factorization needed*)
  SparseArray[Band[{1, 1}] -> c]
  ]
In[87]:= x={{0,1,1,1},{1,0,1,1},{1,1,0,1},{1,1,1,0}}; 
A=x//rationalMatrixForm//Normal
Inverse[A] . X . A
Out[88]= {{0, 3, 0, 0}, {1, 2, 0, 0}, {0, 0, 0, 3}, {0, 0, 1, 2}}
Out[89]= {{-(2/3), 5/3, 1/3, 5/3}, {1/3, 2/3, 1/3, 5/3}, {1/3, 5/
  3, -(2/3), 5/3}, {1/3, 5/3, 1/3, 2/3}}
But the above result is inconsistent with the one given by GAP, as shown below:
 
gap> x:=[[0, 1, 1, 1],
> [1, 0, 1, 1],
> [1, 1, 0, 1],
> [1, 1, 1, 0]];
[ [ 0, 1, 1, 1 ], [ 1, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 1, 1, 1, 0 ] ]
gap> A:=RationalCanonicalFormTransform(x);
[ [ 0, 0, 0, 1 ], [ 1, 0, 0, 1 ], [ -1, 1, 0, 1 ], [ 0, -1, 1, 0 ] ]
gap> A^-1 * x * A;
[ [ -1, 0, 0, 0 ], [ 0, -1, 0, 0 ], [ 0, 0, 0, 3 ], [ 0, 0, 1, 2 ] ]
Any tips for fixing this problem will be appreciated.
Regards, Zhao