summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 988a6bd50bc15008933ba504a0cc6425a8d87517 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use num::{
    bigint::{BigInt, ToBigInt},
    Signed,
};

use berlekamp::Poly;

/// A simple conversion function from anything that can be converted
/// to a big integer to a big rational number.
fn conversion(n: impl ToBigInt) -> BigInt {
    n.to_bigint().unwrap()
}

#[allow(unused)]
fn print_poly(poly: &[BigInt]) {
    struct Monomial(usize);

    impl std::fmt::Display for Monomial {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self.0 {
                0 => Ok(()),
                1 => {
                    write!(f, "x")
                }
                _ => {
                    write!(f, "x^{}", self.0)
                }
            }
        }
    }

    struct Coefficient(BigInt);

    impl std::fmt::Display for Coefficient {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match &self.0 {
                n if n == &conversion(0) || n == &conversion(1) || n == &conversion(-1) => Ok(()),
                _ => {
                    write!(f, "{}", self.0.abs())
                }
            }
        }
    }

    for (n, coeff) in poly.iter().enumerate().rev() {
        if coeff == &conversion(0) {
            continue;
        }

        print!(
            "{}{}{}",
            if n + 1 == poly.len() {
                ""
            } else if coeff >= &conversion(0) {
                " + "
            } else {
                " - "
            },
            Coefficient(coeff.clone()),
            Monomial(n),
        );

        if coeff.abs() == conversion(1) && n == 0 {
            print!("1");
        }
    }

    println!();
}

#[allow(unused)]
macro_rules! print_square_matrix {
    ($s:literal, $g: expr) => {
        print_matrix::<$s, $s, { $s * $s }>($g);
    };
}

fn main() {
    let poly = read_poly(&std::env::args().nth(1).expect("Enter a polynomial"));
    let p = std::env::args()
        .nth(2)
        .expect("Enter a prime")
        .parse::<usize>()
        .unwrap();

    if std::env::args().len() >= 4 {
        // Search for primes modulo which the polynomial is irreducible instead.

        let primes = generate_primes(p);

        println!("Searching {} primes up to {p}...", primes.len());

        for p in primes {
            let factors = berlekamp::factors(&poly, p);

            let total = factors.iter().fold(0usize, |sum, (deg, _)| sum + deg);

            if total == 1 {
                println!("The polynomial {} is irreducible mod {p}", Poly(&poly));

                return;
            }
        }

        println!("The polynomial is reducible modulo primes up to {p}.");

        return;
    }

    // println!("poly is:");
    // print_poly(&poly);

    // println!("prime is {p}");

    // let poly1 = [-20, -21, 0, 1].map(conversion);
    // let poly2 = [1, 3].map(conversion);

    // let composition = berlekamp::composition(&poly1, &poly2);

    // println!(
    //     "the composition of {} and {} is {}",
    //     Poly(&poly1),
    //     Poly(&poly2),
    //     Poly(&composition)
    // );

    // println!("poly2 is {factor}");

    // let poly = [-25, 0, 15, 0, -3, 0, 1].map(conversion);

    // let p = 5;

    let factors = berlekamp::factors(&poly, p);

    print!("{} ≡ ", Poly(&poly));

    let mut total = 0usize;

    for (index, (mul, f)) in factors.into_iter().enumerate() {
        total += mul;

        match mul {
            0 => {
                dbg!("zero multiplicity?");
            }
            1 => {
                print!("{}({})", if index > 0 { " * " } else { "" }, Poly(&f));
            }
            _ => {
                print!(
                    "{}({})^{}",
                    if index > 0 { " * " } else { "" },
                    Poly(&f),
                    mul
                );
            }
        }
    }

    println!(" (mod {p})");

    if total == 1 {
        println!("the polynomial is irreducible");
    }
}

#[allow(unused)]
fn read_poly(s: &str) -> Vec<BigInt> {
    let mut degree: usize;
    let mut coefficient = 1isize;
    let mut pending_coefficient = false;

    let mut iter = s.chars().peekable();

    let mut degrees_and_cos: Vec<(usize, BigInt)> = Vec::new();

    while let Some(c) = iter.next() {
        match c {
            '\n' | '\t' | ' ' => {}
            '+' => {
                if pending_coefficient {
                    degrees_and_cos.push((0usize, conversion(coefficient)));
                }

                pending_coefficient = false;
                coefficient = 1isize;
            }
            'x' => {
                pending_coefficient = false;

                if !matches!(iter.peek(), Some(c) if *c == '^') {
                    degrees_and_cos.push((1usize, conversion(coefficient)));
                    continue;
                }

                let _ = iter.next();

                degree = 0usize;

                while matches!(iter.peek(), Some(c) if c.is_digit(10)) {
                    degree *= 10;
                    degree += iter.next().unwrap() as usize - '0' as usize;
                }

                degrees_and_cos.push((degree, conversion(coefficient)));
            }
            c if c.is_digit(10) || c == '-' => {
                pending_coefficient = true;

                let mut negative = false;

                coefficient = if c.is_digit(10) {
                    c as isize - '0' as isize
                } else {
                    negative = true;
                    -1isize
                };

                let mut first_negative = negative;

                while matches!(iter.peek(), Some(c) if c.is_digit(10)) {
                    if first_negative {
                        coefficient = '0' as isize - iter.next().unwrap() as isize;

                        first_negative = false;

                        continue;
                    }

                    let factor = if negative {
                        '0' as isize - iter.next().unwrap() as isize
                    } else {
                        iter.next().unwrap() as isize - '0' as isize
                    };

                    coefficient *= 10isize;
                    coefficient += factor;
                }
            }
            _ => {
                panic!("invalid: {c}");
            }
        }
    }

    if pending_coefficient {
        degrees_and_cos.push((0usize, conversion(coefficient)));
    }

    let mut degree_co_map: std::collections::HashMap<usize, BigInt> = Default::default();

    for (degree, coefficient) in degrees_and_cos {
        if let Some(orig) = degree_co_map.get(&degree) {
            degree_co_map.insert(degree, orig.clone() + coefficient);
        } else {
            degree_co_map.insert(degree, coefficient);
        }
    }

    // degree_co_map.extend(degrees_and_cos);

    let mut max_degree = 0usize;
    let mut non_zero_p = false;

    for (d, c) in degree_co_map.iter() {
        if c == &conversion(0) {
            continue;
        }

        non_zero_p = true;

        max_degree = std::cmp::max(*d, max_degree);
    }

    if !non_zero_p {
        Vec::new()
    } else {
        let mut result: Vec<_> = std::iter::repeat_with(|| conversion(0))
            .take(max_degree + 1)
            .collect();

        for (d, c) in degree_co_map {
            if c == conversion(0) {
                continue;
            }

            *result.get_mut(d).unwrap() = c;
        }

        result
    }
}

/// Print an array as a square matrix nicely.
///
/// This has the same requirement as the function `power`.  Similarly,
/// one can use the macro `print_square_matrix` to correctly fill in
/// the dimensions automatically.
#[allow(unused)]
fn print_matrix<const X: usize, const Y: usize, const T: usize>(matrix: &[BigInt; T]) {
    if X * Y != T {
        panic!("dimensions do not match: {X} * {Y} is not {T}");
    }

    println!("[");

    let mut max_lens: [usize; Y] = [0; Y];

    for j in 0..Y {
        for i in 0..X {
            let entry_str = format!("{}", matrix.get(Y * i + j).unwrap());

            *max_lens.get_mut(j).unwrap() =
                std::cmp::max(*max_lens.get(j).unwrap(), entry_str.len());
        }
    }

    for i in 0..X {
        print!("  ");

        for j in 0..Y {
            let entry_str = format!("{}", matrix.get(Y * i + j).unwrap());

            let fill_in_space: String = std::iter::repeat(32 as char)
                .take(*max_lens.get(j).unwrap() - entry_str.len())
                .collect();

            print!("{}{} ", fill_in_space, entry_str);
        }

        println!();
    }
    println!("]");
}

#[allow(unused)]
/// Return a vector of primes <= BOUND.
///
/// This is naïve and slow, so BOUND should not be too large.
fn generate_primes(bound: usize) -> Vec<usize> {
    if bound <= 1 {
        return Vec::new();
    }

    let sqrt = (bound as f64).sqrt() as usize;

    let mut result: Vec<usize> = Vec::with_capacity(bound);

    let mut records: Vec<bool> = std::iter::repeat(true).take(bound).collect();

    records[0] = false;
    records[1] = false;

    for i in 2..=(sqrt + 1) {
        if !matches!(records.get(i), Some(true)) {
            continue;
        }

        let mut multiple = i + i;

        while let Some(rec) = records.get_mut(multiple) {
            *rec = false;
            multiple += i;
        }
    }

    result.extend(
        records
            .iter()
            .enumerate()
            .filter_map(|(n, rec)| rec.then_some(n)),
    );

    result
}