gaussiant 0.8.0

Gaussian integers
Documentation
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Gaussian integers in Rust.
//!
//! A [Gaussian integer] is a complex number whose real and imaginary parts are both integers.
//!
//! [Gaussian integer]: https://en.wikipedia.org/wiki/Gaussian_integer
//! [Gaussian prime]: crate::GaussianInt#method.is_gaussian_prime
#![deny(missing_docs)]
#![allow(clippy::needless_return)]

#[cfg(doctest)]
#[macro_use]
extern crate doc_comment;

#[cfg(doctest)]
doctest!("../README.md", readme);

use std::str::FromStr;

use num_complex::{Complex, ParseComplexError};
use num_integer::Integer;
use num_traits::{Num, One, PrimInt, Signed, Zero};

mod ops;

/// A Gaussian integer is a complex number whose real and imaginary parts are both integers.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct GaussianInt<T: PrimInt + Integer>(pub Complex<T>);

/// Creates a new [`GaussianInt`].
///
/// # Example
///
/// ```
/// # use gaussiant::{GaussianInt, gaussint};
/// # fn main() {
/// let z = gaussint!(1, 1);
/// let _z = gaussint!(1, -1);
/// assert_eq!(z * _z, gaussint!(2, 0));
/// # }
/// ```
#[macro_export]
macro_rules! gaussint {
    ($a:expr,$b:expr) => {
        GaussianInt::new($a, $b)
    };
    ($n:expr) => {
        GaussianInt::new($n, 0)
    };
}

impl<T: PrimInt + Integer> GaussianInt<T> {
    /// Creates a new [`GaussianInt`].
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::GaussianInt;
    /// # fn main() {
    /// // 𝑖
    /// let square_root_of_negative_one = GaussianInt::new(0, 1);
    /// # }
    /// ```
    pub fn new(r: T, i: T) -> Self {
        Self(Complex::new(r, i))
    }

    /// Given a Gaussian integer z₀, called a *modulus*,
    /// two Gaussian integers z₁, z₂ are *congruent modulo z₀*,
    /// if their difference is a multiple of z₀.
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::{GaussianInt, gaussint};
    /// # fn main() {
    /// // 2 + 5i ≡ i mod 1 + 2i
    /// let c1 = gaussint!(2, 5);
    /// let c2 = gaussint!(0, 1);
    /// let c3 = gaussint!(1, 2);
    /// assert!(c1.congruent(c2, c3));
    /// # }
    /// ```
    pub fn congruent(&self, other: Self, modulus: Self) -> bool {
        (*self - other) % modulus == Self::zero()
    }
}

impl<T: PrimInt + Integer + Signed> GaussianInt<T> {
    /// Returns the complex conjugate.
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::GaussianInt;
    /// # fn main() {
    /// let z = GaussianInt::new(5, 4);
    /// assert_eq!(z.conj(), GaussianInt::new(5, -4));
    /// # }
    /// ```
    pub fn conj(&self) -> Self {
        Self::new(self.0.re, -self.0.im)
    }

    /// Returns the norm.
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::GaussianInt;
    /// # fn main() {
    /// let z = GaussianInt::new(2, 7);
    /// assert_eq!(z.norm(), 53);
    /// # }
    /// ```
    pub fn norm(&self) -> usize {
        let a = self.0.re;
        let b = self.0.im;
        (T::pow(a, 2) + T::pow(b, 2)).to_usize().unwrap()
    }

    /// Returns `true` if `self` divides `other`.
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::GaussianInt;
    /// # fn main() {
    /// let c1 = GaussianInt::new(5, 0);
    /// let c2 = GaussianInt::new(1, 2);
    /// assert!(c2.divides(c1));
    /// # }
    /// ```
    pub fn divides(&self, other: Self) -> bool {
        *self != Self::zero() && (other % *self) == Self::zero()
    }

    /// Tests whether a Gaussian integer is a rational integer.
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::GaussianInt;
    /// # fn main() {
    /// let z = GaussianInt::new(2, 7);
    /// let z2 = GaussianInt::new(0, -7);
    /// assert!((z + z2).is_rational());
    /// # }
    /// ```
    pub fn is_rational(&self) -> bool {
        self.0.im == T::zero()
    }

    /// Tests for [Gaussian primality].
    ///
    /// A Gaussian integer *a* + *b*i is a *Gaussian prime* if and only if either:
    ///
    /// 1. one of *a*, *b* is zero,
    ///    and the absolute value of the other
    ///    is a prime number of the form 4*n* + 3
    ///    (with *n* a nonnegative integer)
    /// 2. both *a* and *b* are nonzero,
    ///    and *a*² + *b*² is a prime number
    ///    (which will not be of the form 4*n* + 3).
    ///
    /// [Gaussian primality]: https://en.wikipedia.org/wiki/Gaussian_integer#Gaussian_primes
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::GaussianInt;
    /// # fn main() {
    /// let z = GaussianInt::new(2, 7);
    /// assert!(z.is_gaussian_prime());
    /// # }
    /// ```
    pub fn is_gaussian_prime(&self) -> bool {
        let a = self.0.re;
        let b = self.0.im;

        // These numbers would cause integer overflow panics below.
        match (a.abs().to_isize().unwrap(), b.abs().to_isize().unwrap()) {
            (0, 0) => return false,
            (1, 1) => return true,
            (-1, -1) => return true,
            (2, 0) => return false,
            (0, 2) => return false,
            _ => {}
        }

        let condition_1 = match (a.is_zero(), b.is_zero()) {
            (true, false) => {
                let other = b.abs().to_u64().unwrap();
                primal::is_prime(other) && (other - 3) % 4 == 0
            }
            (false, true) => {
                let other = a.abs().to_u64().unwrap();
                primal::is_prime(other) && (other - 3) % 4 == 0
            }
            _ => false,
        };

        let condition_2 = match (a.is_zero(), b.is_zero()) {
            (false, false) => {
                let a = a.abs().to_u64().unwrap();
                let b = b.abs().to_u64().unwrap();
                let sum_of_squares = u64::pow(a, 2) + u64::pow(b, 2);
                let sum_of_squares_is_4n_plus_3 = (sum_of_squares - 3) % 4 == 0;
                primal::is_prime(sum_of_squares) && !sum_of_squares_is_4n_plus_3
            }
            _ => false,
        };

        condition_1 || condition_2
    }

    /// Returns an array of the units of ℤ\[*i*\], the ring of Gaussian integers.
    ///
    /// The units are 1, -1, *i*, -*i*.
    pub fn units() -> [Self; 4] {
        [
            Self::one(),                     //  1
            -Self::one(),                    // -1
            Self::new(T::zero(), T::one()),  //  i
            Self::new(T::zero(), -T::one()), // -i
        ]
    }

    /// Gaussian integers are called associates
    /// if they can be obtained from one another by multiplication by units.
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::GaussianInt;
    /// # fn main() {
    /// let z1 = GaussianInt::new(1, 1);
    /// let z2 = GaussianInt::new(1, -1);
    /// assert!(z1.is_associated(z2));
    /// # }
    /// ```
    pub fn is_associated(&self, other: Self) -> bool {
        for u in GaussianInt::units() {
            if (*self * u) == other {
                return true;
            }
        }
        false
    }

    /// Tests whether a Gaussian integer is "even."
    ///
    /// A Gaussian integer *z* is "even" if *z* ≡ 0 mod 1+*i*.
    ///
    /// See <https://en.wikipedia.org/wiki/Gaussian_integer#Examples>.
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::GaussianInt;
    /// # fn main() {
    /// let z = GaussianInt::new(3, 1);
    /// assert!(z.is_even());
    /// # }
    /// ```
    pub fn is_even(&self) -> bool {
        let modulus = Self::new(T::one(), T::one());
        // self ≡ 0 mod 1+i
        self.congruent(Self::zero(), modulus)
    }

    /// Tests whether a Gaussian integer is "odd."
    ///
    /// A Gaussian integer *z* is "odd" if *z* ≡ 1 mod 1+*i*.
    ///
    /// See <https://en.wikipedia.org/wiki/Gaussian_integer#Examples>.
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::GaussianInt;
    /// # fn main() {
    /// let z = GaussianInt::new(2, 1);
    /// assert!(z.is_odd());
    /// # }
    /// ```
    pub fn is_odd(&self) -> bool {
        let modulus = Self::new(T::one(), T::one());
        // self ≡ 1 mod 1+i
        self.congruent(Self::one(), modulus)
    }
}

impl<T: PrimInt + Integer + Signed> GaussianInt<T>
where
    f64: From<T>,
{
    /// Convert to polar form (r, theta), such that
    /// `self = r * exp(i * theta)`
    ///
    /// # Example
    ///
    /// ```
    /// # use gaussiant::GaussianInt;
    /// # fn main() {
    /// let c = GaussianInt::new(0, 1);
    /// // The polar form of *i* is (1, π/2).
    /// assert_eq!(c.to_polar(), (1f64, std::f64::consts::PI / 2f64));
    /// # }
    /// ```
    pub fn to_polar(&self) -> (f64, f64) {
        let a = self.0.re;
        let b = self.0.im;
        let a: f64 = a.into();
        let b: f64 = b.into();
        Complex::new(a, b).to_polar()
    }
}

/// Returns an iterator of all Gaussian integers *a* + *b*i
/// where |*a*|,|*b*| ≤ `n`.
pub fn get_g_ints(n: isize) -> impl Iterator<Item = GaussianInt<isize>> + 'static {
    let mut integers: Vec<GaussianInt<_>> = vec![];
    for a in -n..=n {
        for b in -n..=n {
            let z = GaussianInt::new(a, b);
            integers.push(z);
        }
    }
    integers.into_iter()
}

/// Returns an iterator of all Gaussian integers *a* + *b*i
/// where *a* is positive (or zero) and |*b*| ≤ `n`.
pub fn get_pos_g_ints(n: isize) -> impl Iterator<Item = GaussianInt<isize>> + 'static {
    let mut pos_integers: Vec<GaussianInt<_>> = vec![];
    for a in 0..=n {
        for b in -n..=n {
            let z = GaussianInt::new(a, b);
            pos_integers.push(z);
        }
    }
    pos_integers.into_iter()
}

/// Returns an iterator of all Gaussian primes *a* + *b*i
/// where |a|,|b| ≤ `n`.
pub fn get_g_primes(n: isize) -> impl Iterator<Item = GaussianInt<isize>> + 'static {
    let set = get_g_ints(n);
    let mut primes: Vec<GaussianInt<_>> = vec![];
    for z in set {
        if z.is_gaussian_prime() {
            primes.push(z);
        }
    }
    primes.into_iter()
}

/// Returns an iterator of all Gaussian primes *a* + *b*i
/// where *a* is positive (or zero) and |*b*| ≤ `n`.
pub fn get_pos_g_primes(n: isize) -> impl Iterator<Item = GaussianInt<isize>> + 'static {
    let set = get_pos_g_ints(n);
    let mut pos_primes: Vec<GaussianInt<_>> = vec![];
    for z in set {
        if z.is_gaussian_prime() {
            pos_primes.push(z);
        }
    }
    pos_primes.into_iter()
}

impl<T: PrimInt + Integer> One for GaussianInt<T> {
    fn one() -> Self {
        GaussianInt::new(T::one(), T::zero())
    }
}

impl<T: PrimInt + Integer> Zero for GaussianInt<T> {
    fn zero() -> Self {
        GaussianInt::new(T::zero(), T::zero())
    }

    fn is_zero(&self) -> bool {
        *self == GaussianInt::zero()
    }
}

impl<T: PrimInt + Integer> From<Complex<T>> for GaussianInt<T> {
    fn from(z: Complex<T>) -> Self {
        Self(z)
    }
}

impl<T: PrimInt + Integer> From<GaussianInt<T>> for isize {
    fn from(g: GaussianInt<T>) -> Self {
        g.0.re.to_isize().unwrap()
    }
}

impl<T> FromStr for GaussianInt<T>
where
    T: PrimInt + Integer + FromStr + Num + Clone,
{
    type Err = ParseComplexError<T::Err>;

    /// Parses `a ± bi`, `ai ± b`, `a`, or `bi` where `a` and `b` are of type `T`.
    ///
    /// # Example
    ///
    /// ```
    /// # use std::str::FromStr;
    /// # use gaussiant::{GaussianInt, gaussint};
    /// # fn main() {
    /// assert_eq!(
    ///     GaussianInt::new(1, 1),
    ///     GaussianInt::from_str("1+i").expect("parse problem!")
    /// );
    /// # }
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::from(Complex::from_str(s)?))
    }
}

impl<T: PrimInt + Integer> std::fmt::Display for GaussianInt<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let one = T::one();
        let zero = T::zero();
        // Can't do -one because self isn't necessarily `Signed`
        let im_is_neg_one = self.0.im + one == zero;

        // a
        if self.0.im == zero {
            return write!(f, "{}", self.0.re.to_isize().unwrap());
        }
        // i
        if self.0.re == zero && self.0.im == T::one() {
            return write!(f, "i");
        }
        // -i
        if self.0.re == zero && im_is_neg_one {
            return write!(f, "-i");
        }
        // bi
        if self.0.re == zero && !im_is_neg_one {
            return write!(f, "{}i", self.0.im.to_isize().unwrap());
        }
        // a+i
        if self.0.im == one {
            return write!(f, "{}+i", self.0.re.to_isize().unwrap());
        }

        if self.0.im < zero {
            // -i
            if self.0.re == zero && im_is_neg_one {
                return write!(f, "-i");
            }
            // a-i
            if self.0.im + one == zero {
                write!(f, "{}-i", self.0.re.to_isize().unwrap(),)
            } else {
                // a-bi
                return write!(
                    f,
                    "{}{}i",
                    self.0.re.to_isize().unwrap(),
                    self.0.im.to_isize().unwrap()
                );
            }
        } else {
            // a+bi
            return write!(
                f,
                "{}+{}i",
                self.0.re.to_isize().unwrap(),
                self.0.im.to_isize().unwrap()
            );
        }
    }
}

#[cfg(test)]
mod tests;