qfall_math/integer_mod_q/z_q/set.rs
1// Copyright 2026 Jan Niklas Siemer
2//
3// This file is part of qFALL-math.
4//
5// qFALL-math is free software: you can redistribute it and/or modify it under
6// the terms of the Mozilla Public License Version 2.0 as published by the
7// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.
8
9//! Implementations to manipulate a [`Zq`] polynomial.
10
11use crate::integer_mod_q::{Modulus, Zq};
12
13impl Zq {
14 /// Changes the modulus of the given [`Zq`] value to the new modulus.
15 /// It takes the representation of `self` in [0, q) as the new
16 /// value and reduces it by the new modulus.
17 ///
18 /// Parameters:
19 /// - `modulus`: the new modulus of the [`Zq`] value
20 ///
21 /// # Examples
22 /// ```
23 /// use qfall_math::integer_mod_q::{Zq, Modulus};
24 /// use std::str::FromStr;
25 ///
26 /// let mut value = Zq::from_str("2 mod 3").unwrap();
27 /// value.change_modulus(2);
28 ///
29 /// assert_eq!("0 mod 2", value.to_string());
30 /// ```
31 ///
32 /// # Panics ...
33 /// - if `modulus` is smaller than `2`.
34 pub fn change_modulus(&mut self, modulus: impl Into<Modulus>) {
35 self.modulus = modulus.into();
36 self.value = self.get_representative_least_nonnegative_residue();
37 self.reduce();
38 }
39}
40
41#[cfg(test)]
42mod test_change_modulus {
43 use super::Zq;
44 use crate::integer_mod_q::Modulus;
45 use std::str::FromStr;
46
47 /// Ensures that the modulus is changed correctly.
48 #[test]
49 fn modulus_correct() {
50 let mut matrix = Zq::from_str("6 mod 7").unwrap();
51 let modulus = Modulus::from(5);
52
53 matrix.change_modulus(&modulus);
54
55 assert_eq!("1 mod 5", matrix.to_string());
56 }
57
58 /// Ensures that the modulus is changed correctly, if the modulus is big.
59 #[test]
60 fn big_modulus_correct() {
61 let mut matrix = Zq::from_str(&format!("6 mod {}", i64::MAX)).unwrap();
62 let modulus = Modulus::from(u64::MAX);
63
64 matrix.change_modulus(&modulus);
65
66 assert_eq!(format!("6 mod {}", u64::MAX), matrix.to_string());
67 }
68
69 /// Ensures that the matrix is reduced correctly.
70 #[test]
71 fn reduced_correct() {
72 let mut matrix = Zq::from_str("6 mod 7").unwrap();
73 let modulus = Modulus::from(2);
74
75 matrix.change_modulus(&modulus);
76
77 assert_eq!("0 mod 2", matrix.to_string());
78 }
79}