Skip to main content

lib_jsl_information/lfsr/
maximum_length_polynomials.rs

1//! Maximum length (primitive) polynomials over GF(2).
2//!
3//! Polynomials are bit masks: bit `k` is the coefficient of `x^k`, so `x^3 + x + 1` is `0b1011`.
4//! An LFSR with a primitive characteristic polynomial of degree `n` produces a maximum-length
5//! sequence of period `2^n - 1`.
6//!
7//! See the book entry [LFSRs and Gold codes](https://jwkunz.github.io/lib_jsl/book/information/lfsr.html#testing-primitivity).
8
9use std::sync::OnceLock;
10
11/// Largest degree supported by [`is_primitive_polynomial`] (limited by trial-division factoring of
12/// `2^n - 1`).
13pub const MAX_CHECKED_DEGREE: u32 = 40;
14
15/// Largest degree in the table returned by [`maximum_length_polynomials`].
16pub const MAX_TABLE_DEGREE: u32 = 32;
17
18fn degree(p: u64) -> u32 {
19    63 - p.leading_zeros()
20}
21
22/// Carry-less multiplication of `a` and `b` modulo `p` (both reduced, degree of `p` at most 63).
23fn mul_mod(mut a: u64, mut b: u64, p: u64) -> u64 {
24    let n = degree(p);
25    let top = 1u64 << n;
26    let mut r = 0u64;
27    while b != 0 {
28        if b & 1 == 1 {
29            r ^= a;
30        }
31        b >>= 1;
32        a <<= 1;
33        if a & top != 0 {
34            a ^= p;
35        }
36    }
37    r
38}
39
40fn pow_mod(base: u64, mut e: u64, p: u64) -> u64 {
41    let mut result = 1u64;
42    let mut b = base;
43    while e > 0 {
44        if e & 1 == 1 {
45            result = mul_mod(result, b, p);
46        }
47        b = mul_mod(b, b, p);
48        e >>= 1;
49    }
50    result
51}
52
53fn prime_factors(mut n: u64) -> Vec<u64> {
54    let mut out = Vec::new();
55    let mut d = 2;
56    while d * d <= n {
57        if n.is_multiple_of(d) {
58            out.push(d);
59            while n.is_multiple_of(d) {
60                n /= d;
61            }
62        }
63        d += 1;
64    }
65    if n > 1 {
66        out.push(n);
67    }
68    out
69}
70
71/// Tests whether `poly` (degree between 2 and [`MAX_CHECKED_DEGREE`], with nonzero constant term)
72/// is primitive over GF(2), i.e. the multiplicative order of `x` modulo `poly` is `2^n - 1`.
73pub fn is_primitive_polynomial(poly: u64) -> bool {
74    if poly < 4 {
75        return false;
76    }
77    let n = degree(poly);
78    if n > MAX_CHECKED_DEGREE || poly & 1 == 0 {
79        return false;
80    }
81    // ANCHOR: primitive
82    let order = (1u64 << n) - 1;
83    // x^order must be 1 and x^(order/q) != 1 for every prime q dividing order.
84    if pow_mod(2, order, poly) != 1 {
85        return false;
86    }
87    prime_factors(order).into_iter().all(|q| pow_mod(2, order / q, poly) != 1)
88    // ANCHOR_END: primitive
89}
90
91/// Returns a minimal-weight primitive polynomial of the given degree (`2..=32`): a trinomial where
92/// one exists, otherwise a pentanomial or heptanomial, taking the numerically smallest.
93pub fn maximum_length_polynomial(degree: u32) -> Option<u64> {
94    if !(2..=MAX_TABLE_DEGREE).contains(&degree) {
95        return None;
96    }
97    maximum_length_polynomials().get(degree as usize - 2).copied()
98}
99
100/// Calls `f` with every mask built from `count` distinct bits chosen among bits `1..n`, in
101/// increasing numeric order of the resulting masks; stops early when `f` returns `true`.
102fn combos(n: u32, count: u32, f: &mut dyn FnMut(u64) -> bool) -> bool {
103    fn rec(start: u32, n: u32, left: u32, acc: u64, f: &mut dyn FnMut(u64) -> bool) -> bool {
104        if left == 0 {
105            return f(acc);
106        }
107        for b in start..n {
108            if n - b < left {
109                break;
110            }
111            if rec(b + 1, n, left - 1, acc | (1 << b), f) {
112                return true;
113            }
114        }
115        false
116    }
117    rec(1, n, count, 0, f)
118}
119
120fn minimal_weight_primitive(n: u32) -> u64 {
121    let base = (1u64 << n) | 1;
122    for mid_terms in [1, 3, 5, 7, 9] {
123        let mut best: Option<u64> = None;
124        combos(n, mid_terms, &mut |m| {
125            let p = base | m;
126            if is_primitive_polynomial(p) {
127                best = Some(best.map_or(p, |b| b.min(p)));
128            }
129            false
130        });
131        if let Some(p) = best {
132            return p;
133        }
134    }
135    unreachable!("a primitive polynomial of weight <= 11 exists for every degree up to 32")
136}
137
138/// Returns one primitive polynomial for each degree `2..=32`; element `i` has degree `i + 2`.
139/// Each has minimal weight (number of nonzero terms).
140pub fn maximum_length_polynomials() -> Vec<u64> {
141    static TABLE: OnceLock<Vec<u64>> = OnceLock::new();
142    TABLE
143        .get_or_init(|| (2..=MAX_TABLE_DEGREE).map(minimal_weight_primitive).collect())
144        .clone()
145}
146
147/// Enumerates every primitive polynomial of the given degree (`2..=24`).
148pub fn all_maximum_length_polynomials(degree: u32) -> Vec<u64> {
149    if !(2..=24).contains(&degree) {
150        return Vec::new();
151    }
152    let base = (1u64 << degree) | 1;
153    (0..(1u64 << (degree - 1)))
154        .map(|k| base | (k << 1))
155        .filter(|&p| is_primitive_polynomial(p))
156        .collect()
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use crate::lfsr::Lfsr;
163
164    #[test]
165    fn known_small_polynomials() {
166        assert_eq!(maximum_length_polynomial(2), Some(0b111));
167        assert_eq!(maximum_length_polynomial(3), Some(0b1011));
168        assert_eq!(maximum_length_polynomial(4), Some(0b10011));
169        assert_eq!(maximum_length_polynomial(5), Some(0b100101));
170        assert!(is_primitive_polynomial(0b1011) && is_primitive_polynomial(0b1101));
171        assert!(!is_primitive_polynomial(0b10101));
172        assert!(!is_primitive_polynomial(0b11111)); // x^4+x^3+x^2+x+1 is irreducible, order 5
173        assert_eq!(maximum_length_polynomial(1), None);
174    }
175
176    #[test]
177    fn counts_match_euler_phi() {
178        // Number of primitive polynomials of degree n is phi(2^n - 1) / n.
179        assert_eq!(all_maximum_length_polynomials(2).len(), 1);
180        assert_eq!(all_maximum_length_polynomials(3).len(), 2);
181        assert_eq!(all_maximum_length_polynomials(4).len(), 2);
182        assert_eq!(all_maximum_length_polynomials(5).len(), 6);
183        assert_eq!(all_maximum_length_polynomials(6).len(), 6);
184        assert_eq!(all_maximum_length_polynomials(8).len(), 16);
185        assert_eq!(all_maximum_length_polynomials(10).len(), 60);
186    }
187
188    #[test]
189    fn table_polynomials_generate_maximal_sequences() {
190        let table = maximum_length_polynomials();
191        assert_eq!(table.len(), 31);
192        for (i, &p) in table.iter().enumerate() {
193            let n = i as u32 + 2;
194            assert_eq!(degree(p), n);
195            if n <= 12 {
196                assert_eq!(Lfsr::from_polynomial(p, 1).period(1 << 13), Some((1 << n) - 1), "degree {n}");
197            }
198        }
199        assert!(table.iter().skip(2).all(|&p| p.count_ones() <= 5));
200    }
201}