/* One step of the occupied-column transfer for bounded-displacement derangements. A host supplies the table of predecessors. No system headers or C runtime are needed. */ #ifdef _WIN32 #define EXPORT __declspec(dllexport) int transfer_dll_start(void *module, unsigned reason, void *reserved) { (void)module; (void)reason; (void)reserved; return 1; } #else #define EXPORT #endif static unsigned inverse65521(unsigned a) { unsigned power = 65519, result = 1; while (power) { if (power & 1) result = (result*a) % 65521; a = (a*a) % 65521; power >>= 1; } return result; } /* Classical Berlekamp--Massey with Q(0)=1. The caller zeros the three buffers of length count+1. Every discrepancy sum must fit uint64. */ EXPORT unsigned minimal65521(const unsigned *s, unsigned count, unsigned *c, unsigned *b, unsigned *tmp) { unsigned n, j, degree = 0, last_degree = 0, shift = 1, inv = 1; c[0] = b[0] = 1; for (n = 0; n < count; ++n) { unsigned long long total = s[n]; unsigned delta, scale, grow; for (j = 1; j <= degree; ++j) total += (unsigned long long)c[j]*s[n-j]; delta = (unsigned)(total % 65521); if (delta == 0) { ++shift; continue; } grow = (2*degree <= n); if (grow) for (j = 0; j <= degree; ++j) tmp[j] = c[j]; scale = 65521 - (delta*inv)%65521; for (j = 0; j <= last_degree; ++j) c[shift+j] = (c[shift+j] + scale*b[j]) % 65521; if (grow) { for (j = 0; j <= degree; ++j) b[j] = tmp[j]; last_degree = degree; degree = n+1-degree; shift = 1; inv = inverse65521(delta); } else ++shift; } return degree; } EXPORT void transfer_terms(unsigned width, unsigned states, unsigned prime, const unsigned *parents, const unsigned *unique, unsigned *current, unsigned *scratch, unsigned count, unsigned *terms) { unsigned half = states / 2; unsigned i, t, j; for (t = 0; t < count; ++t) { terms[t] = current[0]; for (i = 0; i < half; ++i) { const unsigned *p = parents + i * (width + 1); unsigned s = 0; if (width == 10) { s = current[p[0]] + current[p[1]] + current[p[2]] + current[p[3]] + current[p[4]] + current[p[5]] + current[p[6]] + current[p[7]] + current[p[8]] + current[p[9]] + current[p[10]]; } else { for (j = 0; j <= width; ++j) s += current[p[j]]; } scratch[i] = prime == 65521 ? s % 65521 : s % prime; } for (i = 0; i < half; ++i) scratch[half+i] = current[unique[i]]; { unsigned *swap = current; current = scratch; scratch = swap; } } }