We are looking for an algorithm with the following criteria.
Input is an arbitrary positive integer (n), that represents the length of the compare subse
An n-bit linear feedback shift register, if it can operate at maximum period, must meet most of the requirements. This is because its operating state is the size of the test window. If ever a bit pattern occurred more than once then its state would have reverted to a previous state and its period would be shorter than expected.
Unfortunately an LFSR cannot run with a state of zero. To overcome this, simply append zeroes to the beginning of the bit string.
void generate(int n) {
static const uint64_t polytab[64] = {
0x2, 0x2, 0x6, 0xc,
0x18, 0x28, 0x60, 0xc0,
0x170,0x220, 0x480, 0xa00,
0x1052, 0x201a, 0x402a, 0xc000,
/* table can be completed from:
* http://www.xilinx.com/support/documentation/application_notes/xapp052.pdf
*/
};
uint64_t poly = polytab[n];
uint64_t m = ~(-2ll << (n - 1));
uint64_t s = 1;
for (i = 0; i < n; i++) emit(0);
do {
emit(s & 1);
s <<= 1;
s = (s + parity(s & poly)) & m;
} while (s != 1);
}
If you need a test window longer than 64 bits then just use 64 bits (or if you must you can extend the arithmetic to 128 bits). Beyond 64 bits some other resource will be exhausted before it is discovered that the bit string is not maximum length.
For completeness, a parity function:
int parity(uint64_t m) {
int p = 0;
while (m != 0) {
m &= m - 1;
p ^= 1;
}
return p;
}
Outputs for n=3, 4, and 5:
3: 0001011100
4: 0000100110101111000
5: 000001001011001111100011011101010000