def gf_berlekamp(f, p, K):
 Q = gf_Qmatrix(f, p, K)
 V = gf_Qbasis(Q, p, K)
 for (i, v) in enumerate(V):
  V[i] = gf_strip(list(reversed(v)))
 factors = [f]
 for k in range(1, len(V)):
  for f in list(factors):
   s = K.zero
   while (s < p):
    g = gf_sub_ground(V[k], s, p, K)
    h = gf_gcd(f, g, p, K)
    if ((h != [K.one]) and (h != f)):
     factors.remove(f)
     f = gf_quo(f, h, p, K)
     factors.extend([f, h])
    if (len(factors) == len(V)):
     return _sort_factors(factors, multiple=False)
    s += K.one
 return _sort_factors(factors, multiple=False)

def gf_berlekamp ( f , p , K ) : Q = gf_Qmatrix ( f , p , K ) V = gf_Qbasis ( Q , p , K ) for ( i , v ) in enumerate ( V ) : V [ i ] = gf_strip ( list ( reversed ( v ) ) ) factors = [ f ] for k in range ( 1 , len ( V ) ) : for f in list ( factors ) : s = K . zero while ( s < p ) : g = gf_sub_ground ( V [ k ] , s , p , K ) h = gf_gcd ( f , g , p , K ) if ( ( h != [ K . one ] ) and ( h != f ) ) : factors . remove ( f ) f = gf_quo ( f , h , p , K ) factors . extend ( [ f , h ] ) if ( len ( factors ) == len ( V ) ) : return _sort_factors ( factors , multiple = False ) s += K . one return _sort_factors ( factors , multiple = False )
factor a square-free f in gf(p)[x] for small p .