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
483
484
485
486
487
488
489
490
491
492
493
use std::{
    cmp::Ordering,
    fmt::{self, Debug, Display, Formatter},
    ops,
};

use malachite::{
    self as mal,
    num::{
        arithmetic::traits::{Abs, Gcd, DivRem, PowAssign, Sign as MalSign},
        conversion::traits::IsInteger,
    },
};
use ref_cast::RefCast;

#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RefCast)]
#[repr(transparent)]
pub struct Int(mal::Integer);

impl Int {
    pub const ZERO: Int = Int(mal::Integer::const_from_signed(0));
    pub const ONE: Int = Int(mal::Integer::const_from_signed(1));
    pub const TWO: Int = Int(mal::Integer::const_from_signed(2));

    pub fn binomial_coeff(n: &Int, k: &Int) -> Int {
        Self(mal::num::arithmetic::traits::BinomialCoefficient::binomial_coefficient(&n.0, &k.0))
    }

    pub fn range_inclusive(start: Self, stop: Self) -> num::iter::RangeInclusive<Int> {
        num::iter::range_inclusive(start, stop)
    }

    pub fn is_one(&self) -> bool {
        self == &Int::ONE
    }

    pub fn is_zero(&self) -> bool {
        self == &Int::ZERO
    }

    pub fn gcd(&self, other: &Self) -> Self {
        let n = self.0.unsigned_abs_ref().gcd(other.0.unsigned_abs_ref());
        Self(n.into())
    }
}

impl fmt::Debug for Int {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}
impl fmt::Display for Int {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl num::One for Int {
    fn one() -> Self {
        Int::ONE
    }
}

impl num::ToPrimitive for Int {
    fn to_i64(&self) -> Option<i64> {
        i64::try_from(&self.0).ok()
    }

    fn to_u64(&self) -> Option<u64> {
        u64::try_from(&self.0).ok()
    }

    fn to_u128(&self) -> Option<u128> {
        u128::try_from(&self.0).ok()
    }

    fn to_i128(&self) -> Option<i128> {
        i128::try_from(&self.0).ok()
    }
}

impl TryFrom<Rational> for Int {
    type Error = ();
    fn try_from(value: Rational) -> Result<Self, Self::Error> {
        match value.to_int() {
            Some(int) => Ok(int),
            None => Err(()),
        }
    }
}
impl From<Int> for Rational {
    fn from(value: Int) -> Self {
        Rational::from(value.0)
    }
}
impl From<u64> for Int {
    fn from(value: u64) -> Self {
        Self(mal::Integer::from(value))
    }
}

impl ops::Add for Int {
    type Output = Int;
    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}
impl ops::AddAssign for Int {
    fn add_assign(&mut self, rhs: Self) {
        self.0 = self.0.clone() + rhs.0;
    }
}
impl ops::AddAssign<&Int> for Int {
    fn add_assign(&mut self, rhs: &Self) {
        self.0 = self.0.clone() + &rhs.0;
    }
}
impl ops::Add<&Int> for Int {
    type Output = Int;
    fn add(self, rhs: &Self) -> Self::Output {
        Self(self.0 + &rhs.0)
    }
}
impl ops::Sub for Int {
    type Output = Int;
    fn sub(self, rhs: Self) -> Self::Output {
        Self(self.0 - rhs.0)
    }
}
impl ops::SubAssign for Int {
    fn sub_assign(&mut self, rhs: Self) {
        self.0 = self.0.clone() - rhs.0;
    }
}
impl ops::SubAssign<&Int> for Int {
    fn sub_assign(&mut self, rhs: &Self) {
        self.0 = self.0.clone() - &rhs.0;
    }
}
impl ops::Sub<&Int> for Int {
    type Output = Int;
    fn sub(self, rhs: &Self) -> Self::Output {
        Self(self.0 - &rhs.0)
    }
}
impl ops::Mul for Int {
    type Output = Int;
    fn mul(self, rhs: Self) -> Self::Output {
        Self(self.0 * rhs.0)
    }
}
impl ops::MulAssign for Int {
    fn mul_assign(&mut self, rhs: Self) {
        self.0 = self.0.clone() * rhs.0;
    }
}
impl ops::MulAssign<&Int> for Int {
    fn mul_assign(&mut self, rhs: &Self) {
        self.0 = self.0.clone() * &rhs.0;
    }
}
impl ops::Mul<&Int> for Int {
    type Output = Int;
    fn mul(self, rhs: &Self) -> Self::Output {
        Self(self.0 * &rhs.0)
    }
}
impl ops::Div for Int {
    type Output = Int;
    fn div(self, rhs: Self) -> Self::Output {
        Self(self.0 / rhs.0)
    }
}
impl ops::Div<&Int> for Int {
    type Output = Int;
    fn div(self, rhs: &Self) -> Self::Output {
        Self(self.0 / &rhs.0)
    }
}
impl ops::DivAssign for Int {
    fn div_assign(&mut self, rhs: Self) {
        self.0 = self.0.clone() / rhs.0;
    }
}
impl ops::DivAssign<&Int> for Int {
    fn div_assign(&mut self, rhs: &Self) {
        self.0 = self.0.clone() / &rhs.0;
    }
}

#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Rational(pub(crate) mal::Rational);

impl Rational {
    pub const MINUS_TWO: Self = Rational(mal::Rational::const_from_signed(-2));
    pub const MINUS_ONE: Self = Rational(mal::Rational::const_from_signed(-1));
    pub const ZERO: Self = Rational(mal::Rational::const_from_signed(0));
    pub const ONE: Self = Rational(mal::Rational::const_from_signed(1));
    pub const TWO: Self = Rational(mal::Rational::const_from_signed(2));

    pub const fn new_int(n: i64) -> Self {
        Rational(mal::Rational::const_from_signed(n))
    }

    pub fn numer(&self) -> Int {
        Int(mal::Integer::from(self.0.numerator_ref().clone()))
        //UInt::ref_cast(self.0.numerator_ref())
    }

    pub fn to_int(&self) -> Option<Int> {
        Some(Int(mal::Integer::try_from(self.0.clone()).ok()?))
    }

    pub fn denom(&self) -> Int {
        Int(mal::Integer::from(self.0.denominator_ref().clone()))
    }

    #[inline(always)]
    pub fn is_zero(&self) -> bool {
        matches!(self.0.sign(), Ordering::Equal)
    }
    pub fn is_one(&self) -> bool {
        self == &Rational::ONE
    }
    #[inline(always)]
    pub fn is_pos(&self) -> bool {
        matches!(self.0.sign(), Ordering::Greater)
    }
    #[inline(always)]
    pub fn is_neg(&self) -> bool {
        matches!(self.0.sign(), Ordering::Less)
    }

    #[inline(always)]
    pub fn is_int(&self) -> bool {
        self.0.is_integer()
    }

    /// none if [self] is zero
    #[inline(always)]
    pub fn inverse(self) -> Option<Self> {
        if self.is_zero() {
            None
        } else {
            let is_neg = self.is_neg();
            let (num, denom) = self.0.to_numerator_and_denominator();
            let mut r = mal::Rational::from_naturals(denom, num);
            // num and denom are unsigned
            if is_neg {
                r *= Rational::MINUS_ONE.0;
            }
            Some(Self(r))
        }
    }

    pub fn abs(self) -> Self {
        Self(self.0.abs())
    }

    pub fn div_rem(&self) -> (Self, Self) {
        let denom = self.denom();
        let (num, den) = self.0.to_numerator_and_denominator();
        let (quot, rem) = num.div_rem(den);
        (Self(mal::Rational::from(quot)), (Self(mal::Rational::from(rem)) / Self::from(denom)).unwrap())

    }

    /// will calculate [self] to the power of an integer number.
    ///
    /// if the exponent is (a/b) non-int: we calculate the power to the int quotient of a/b
    /// and return the remainder: (self^quot, rem).
    ///
    /// n^(a/b) = n^(quot + rem) = n^(quot) * n^(rem) -> (n^quot, rem)
    ///
    /// quot: Int, rest: Fraction, n^(quot): Rational
    ///
    /// returns the input if calculation was not possible
    pub fn pow(mut self, mut rhs: Self) -> (Self, Self) {
        if self.is_zero() && rhs.is_zero() {
            panic!("0^0");
        }

        if rhs.is_zero() {
            return (Rational::ONE, Rational::ZERO);
        }

        // inverse if exponent is negative
        if rhs.is_neg() {
            self = self.inverse().unwrap();
            rhs = rhs.abs();
        }

        debug_assert!(rhs.is_pos());

        if rhs.is_int() {
            let exp = rhs.0.numerator_ref();
            if let Ok(exp) = u64::try_from(exp) {
                self.0.pow_assign(exp);
                return (self, Rational::ZERO);
            } else {
                return (self, rhs);
            }
        }

        // ensure that the exponent is < 1
        // a^(b/c) -> ( b/c -> quot + rem ) -> a^quot * a^rem  // apply the quotient
        if rhs.0.numerator_ref() > rhs.0.denominator_ref() {
            let (num, den) = rhs.0.to_numerator_and_denominator();
            let (quot, rem) = num.div_rem(den);
            let rem_exp = Self(mal::Rational::from(rem));

            if let Ok(apply_exp) = u64::try_from(&quot) {
                self.0.pow_assign(apply_exp);
                return (self, rem_exp);
            }
        }

        // no change
        (self, rhs)
    }

    pub fn pow_basic(self, rhs: Self) -> Option<Self> {
        let (pow, rest) = self.pow(rhs);
        if rest != Rational::ZERO {
            None
        } else {
            Some(pow)
        }
    }
}

impl ops::Add for Rational {
    type Output = Self;

    #[inline(always)]
    fn add(mut self, rhs: Self) -> Self::Output {
        self.0 += rhs.0;
        self
    }
}
impl ops::Add<&Rational> for Rational {
    type Output = Self;

    #[inline(always)]
    fn add(mut self, rhs: &Self) -> Self::Output {
        self.0 += &rhs.0;
        self
    }
}
impl ops::AddAssign for Rational {
    fn add_assign(&mut self, rhs: Self) {
        self.0 += rhs.0;
    }
}
impl ops::AddAssign<&Rational> for Rational {
    fn add_assign(&mut self, rhs: &Self) {
        self.0 += &rhs.0;
    }
}
impl ops::Sub for Rational {
    type Output = Self;

    #[inline(always)]
    fn sub(mut self, rhs: Self) -> Self::Output {
        self.0 -= rhs.0;
        self
    }
}
impl ops::Sub<&Rational> for Rational {
    type Output = Self;

    #[inline(always)]
    fn sub(mut self, rhs: &Self) -> Self::Output {
        self.0 -= &rhs.0;
        self
    }
}
impl ops::SubAssign for Rational {
    fn sub_assign(&mut self, rhs: Self) {
        self.0 -= rhs.0;
    }
}
impl ops::SubAssign<&Rational> for Rational {
    fn sub_assign(&mut self, rhs: &Self) {
        self.0 -= &rhs.0;
    }
}
impl ops::Mul for Rational {
    type Output = Self;

    #[inline(always)]
    fn mul(mut self, rhs: Self) -> Self::Output {
        self.0 *= rhs.0;
        self
    }
}
impl ops::Mul<&Rational> for Rational {
    type Output = Self;

    #[inline(always)]
    fn mul(mut self, rhs: &Self) -> Self::Output {
        self.0 *= &rhs.0;
        self
    }
}
impl ops::MulAssign for Rational {
    fn mul_assign(&mut self, rhs: Self) {
        self.0 *= rhs.0;
    }
}
impl ops::MulAssign<&Rational> for Rational {
    fn mul_assign(&mut self, rhs: &Self) {
        self.0 *= &rhs.0;
    }
}
impl ops::Div for Rational {
    type Output = Option<Self>;

    #[inline(always)]
    fn div(mut self, rhs: Self) -> Self::Output {
        if rhs.is_zero() {
            None
        } else {
            self.0 /= rhs.0;
            Some(self)
        }
    }
}
impl ops::Div<&Rational> for Rational {
    type Output = Option<Self>;

    #[inline(always)]
    fn div(mut self, rhs: &Self) -> Self::Output {
        if rhs.is_zero() {
            None
        } else {
            self.0 /= &rhs.0;
            Some(self)
        }
    }
}

impl From<u128> for Rational {
    fn from(value: u128) -> Self {
        Self(mal::Rational::from(value))
    }
}
impl From<i64> for Rational {
    fn from(value: i64) -> Self {
        Self(mal::Rational::from(value))
    }
}
impl From<i32> for Rational {
    fn from(value: i32) -> Self {
        Self(mal::Rational::from(value))
    }
}
impl From<mal::Integer> for Rational {
    fn from(value: mal::Integer) -> Self {
        Self(mal::Rational::from(value))
    }
}
impl From<(u64, u64)> for Rational {
    fn from(value: (u64, u64)) -> Self {
        let n = mal::Integer::from(value.0);
        let d = mal::Integer::from(value.1);
        Self(mal::Rational::from_integers(n, d))
    }
}
impl From<(i64, i64)> for Rational {
    fn from(value: (i64, i64)) -> Self {
        let is_neg = (value.0 * value.1) < 0;
        let n = mal::Integer::from(value.0.unsigned_abs());
        let d = mal::Integer::from(value.1.unsigned_abs());
        let mut r = mal::Rational::from_integers(n, d);

        if is_neg {
            r *= Rational::MINUS_ONE.0;
        }
        Self(r)
    }
}

impl Display for Rational {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}
impl Debug for Rational {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}