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
//! Rational numbers.
#[cfg(test)]
mod tests;

use numext_fixed_uint::U256;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt;
use std::ops::{Add, Div, Mul, Sub};

/// Represents the ratio `numerator / denominator`, where `numerator` and `denominator` are both
/// unsigned 256-bit integers.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct RationalU256 {
    /// Numerator.
    numer: U256,
    /// Denominator.
    denom: U256,
}

impl fmt::Display for RationalU256 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/{}", self.numer, self.denom)
    }
}

impl RationalU256 {
    /// Creates a new ratio `numer / denom`.
    ///
    /// ## Panics
    ///
    /// Panics when `denom` is zero.
    #[inline]
    pub fn new(numer: U256, denom: U256) -> RationalU256 {
        if denom.is_zero() {
            panic!("denominator == 0");
        }
        let mut ret = RationalU256::new_raw(numer, denom);
        ret.reduce();
        ret
    }

    /// Creates a new ratio `numer / denom` without checking whether `denom` is zero.
    #[inline]
    pub const fn new_raw(numer: U256, denom: U256) -> RationalU256 {
        RationalU256 { numer, denom }
    }

    /// Creates a new ratio `t / 1`.
    #[inline]
    pub const fn from_u256(t: U256) -> RationalU256 {
        RationalU256::new_raw(t, U256::one())
    }

    /// Tells whether the numerator is zero.
    #[inline]
    pub fn is_zero(&self) -> bool {
        self.numer.is_zero()
    }

    /// Creates a new ratio `0 / 1`.
    #[inline]
    pub const fn zero() -> RationalU256 {
        RationalU256::new_raw(U256::zero(), U256::one())
    }

    /// Creates a new ratio `1 / 1`.
    #[inline]
    pub const fn one() -> RationalU256 {
        RationalU256::new_raw(U256::one(), U256::one())
    }

    /// Rounds down the ratio into an unsigned 256-bit integer.
    #[inline]
    pub fn into_u256(self) -> U256 {
        self.numer / self.denom
    }

    /// Computes `self - rhs` and saturates the result to zero when `self` is less than `rhs`.
    ///
    /// Returns `self - rhs` when `self > rhs`, returns zero otherwise.
    #[inline]
    pub fn saturating_sub(self, rhs: RationalU256) -> Self {
        if self.denom == rhs.denom {
            let (numer, overflowing) = self.numer.overflowing_sub(&rhs.numer);
            return if overflowing {
                RationalU256::zero()
            } else {
                RationalU256::new(numer, self.denom)
            };
        }

        let gcd = self.denom.gcd(&rhs.denom);
        let lcm = &self.denom * (&rhs.denom / gcd);
        let lhs_numer = &self.numer * (&lcm / self.denom);
        let rhs_numer = &rhs.numer * (&lcm / &rhs.denom);

        let (numer, overflowing) = lhs_numer.overflowing_sub(&rhs_numer);
        if overflowing {
            RationalU256::zero()
        } else {
            RationalU256::new(numer, lcm)
        }
    }

    /// Computes `self - rhs` and saturates the result to zero when `self` is less than `rhs`.
    ///
    /// Returns `self - rhs` when `self > rhs`, returns zero otherwise.
    #[inline]
    pub fn saturating_sub_u256(self, rhs: U256) -> Self {
        let (numer, overflowing) = self.numer.overflowing_sub(&(&self.denom * rhs));
        if overflowing {
            RationalU256::zero()
        } else {
            RationalU256::new_raw(numer, self.denom)
        }
    }

    /// Puts self into lowest terms, with denom > 0.
    fn reduce(&mut self) {
        let g = self.numer.gcd(&self.denom);
        self.numer = &self.numer / &g;
        self.denom = &self.denom / &g;
    }
}

// a/b * c/d = (a/gcd_ad)*(c/gcd_bc) / ((d/gcd_ad)*(b/gcd_bc))
impl Mul<&RationalU256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn mul(self, rhs: &RationalU256) -> RationalU256 {
        let gcd_ad = self.numer.gcd(&rhs.denom);
        let gcd_bc = self.denom.gcd(&rhs.numer);

        RationalU256::new_raw(
            (&self.numer / &gcd_ad) * (&rhs.numer / &gcd_bc),
            (&self.denom / gcd_bc) * (&rhs.denom / gcd_ad),
        )
    }
}

impl Mul<RationalU256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn mul(self, rhs: RationalU256) -> RationalU256 {
        self.mul(&rhs)
    }
}

impl Mul<&RationalU256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn mul(self, rhs: &RationalU256) -> RationalU256 {
        (&self).mul(rhs)
    }
}

impl Mul<RationalU256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn mul(self, rhs: RationalU256) -> RationalU256 {
        (&self).mul(&rhs)
    }
}

// a/b * c/1 = (a*c) / (b*1) = (a*c) / b
impl Mul<&U256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn mul(self, rhs: &U256) -> RationalU256 {
        let gcd = self.denom.gcd(&rhs);
        RationalU256::new_raw(&self.numer * (rhs.div(&gcd)), (&self.denom).div(gcd))
    }
}

impl Mul<U256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn mul(self, rhs: U256) -> RationalU256 {
        self.mul(&rhs)
    }
}

impl Mul<U256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn mul(self, rhs: U256) -> RationalU256 {
        (&self).mul(&rhs)
    }
}

impl Mul<&U256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn mul(self, rhs: &U256) -> RationalU256 {
        (&self).mul(rhs)
    }
}

// (a/b) / (c/d) = (a/gcd_ac)*(d/gcd_bd) / ((c/gcd_ac)*(b/gcd_bd))
impl Div<&RationalU256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn div(self, rhs: &RationalU256) -> RationalU256 {
        let gcd_ac = self.numer.gcd(&rhs.numer);
        let gcd_bd = self.denom.gcd(&rhs.denom);
        RationalU256::new_raw(
            (&self.numer / &gcd_ac) * (&rhs.denom / &gcd_bd),
            (&self.denom / gcd_bd) * (&rhs.numer / gcd_ac),
        )
    }
}

impl Div<RationalU256> for RationalU256 {
    type Output = RationalU256;

    #[inline]
    fn div(self, rhs: RationalU256) -> RationalU256 {
        (&self).div(&rhs)
    }
}

impl Div<RationalU256> for &RationalU256 {
    type Output = RationalU256;

    #[inline]
    fn div(self, rhs: RationalU256) -> RationalU256 {
        (&self).div(&rhs)
    }
}

impl Div<&RationalU256> for RationalU256 {
    type Output = RationalU256;

    #[inline]
    fn div(self, rhs: &RationalU256) -> RationalU256 {
        (&self).div(rhs)
    }
}

// (a/b) / (c/1) = (a*1) / (b*c) = a / (b*c)
impl Div<&U256> for &RationalU256 {
    type Output = RationalU256;

    #[inline]
    fn div(self, rhs: &U256) -> RationalU256 {
        let gcd = self.numer.gcd(&rhs);
        RationalU256::new_raw(&self.numer / &gcd, &self.denom * (rhs / gcd))
    }
}

impl Div<U256> for RationalU256 {
    type Output = RationalU256;

    #[inline]
    fn div(self, rhs: U256) -> RationalU256 {
        (&self).div(&rhs)
    }
}

impl Div<&U256> for RationalU256 {
    type Output = RationalU256;

    #[inline]
    fn div(self, rhs: &U256) -> RationalU256 {
        (&self).div(rhs)
    }
}

impl Div<U256> for &RationalU256 {
    type Output = RationalU256;

    #[inline]
    fn div(self, rhs: U256) -> RationalU256 {
        (self).div(&rhs)
    }
}

impl Add<&RationalU256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn add(self, rhs: &RationalU256) -> RationalU256 {
        if self.denom == rhs.denom {
            RationalU256::new(&self.numer + &rhs.numer, self.denom.clone())
        } else {
            let gcd = self.denom.gcd(&rhs.denom);
            let lcm = &self.denom * (&rhs.denom / gcd);
            let lhs_numer = &self.numer * (&lcm / &self.denom);
            let rhs_numer = &rhs.numer * (&lcm / &rhs.denom);

            RationalU256::new(lhs_numer + rhs_numer, lcm)
        }
    }
}

impl Add<RationalU256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn add(self, rhs: RationalU256) -> RationalU256 {
        (&self).add(&rhs)
    }
}

impl Add<&RationalU256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn add(self, rhs: &RationalU256) -> RationalU256 {
        (&self).add(rhs)
    }
}

impl Add<RationalU256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn add(self, rhs: RationalU256) -> RationalU256 {
        (self).add(&rhs)
    }
}

impl Add<&U256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn add(self, rhs: &U256) -> RationalU256 {
        RationalU256::new_raw(&self.numer + (&self.denom * rhs), self.denom.clone())
    }
}

impl Add<U256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn add(self, rhs: U256) -> RationalU256 {
        (&self).add(&rhs)
    }
}

impl Add<&U256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn add(self, rhs: &U256) -> RationalU256 {
        (&self).add(rhs)
    }
}

impl Add<U256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn add(self, rhs: U256) -> RationalU256 {
        self.add(&rhs)
    }
}

impl Sub<&RationalU256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn sub(self, rhs: &RationalU256) -> RationalU256 {
        if self.denom == rhs.denom {
            RationalU256::new(&self.numer - &rhs.numer, self.denom.clone())
        } else {
            let gcd = self.denom.gcd(&rhs.denom);
            let lcm = &self.denom * (&rhs.denom / gcd);
            let lhs_numer = &self.numer * (&lcm / &self.denom);
            let rhs_numer = &rhs.numer * (&lcm / &rhs.denom);

            RationalU256::new(lhs_numer - rhs_numer, lcm)
        }
    }
}

impl Sub<RationalU256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn sub(self, rhs: RationalU256) -> RationalU256 {
        (&self).sub(&rhs)
    }
}

impl Sub<&RationalU256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn sub(self, rhs: &RationalU256) -> RationalU256 {
        (&self).sub(rhs)
    }
}

impl Sub<RationalU256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn sub(self, rhs: RationalU256) -> RationalU256 {
        (&self).sub(&rhs)
    }
}

impl Sub<&U256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn sub(self, rhs: &U256) -> RationalU256 {
        RationalU256::new_raw(&self.numer - (&self.denom * rhs), self.denom.clone())
    }
}

impl Sub<U256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn sub(self, rhs: U256) -> RationalU256 {
        (&self).sub(&rhs)
    }
}

impl Sub<&U256> for RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn sub(self, rhs: &U256) -> RationalU256 {
        (&self).sub(rhs)
    }
}

impl Sub<U256> for &RationalU256 {
    type Output = RationalU256;
    #[inline]
    fn sub(self, rhs: U256) -> RationalU256 {
        self.sub(&rhs)
    }
}

impl PartialOrd for RationalU256 {
    fn partial_cmp(&self, other: &RationalU256) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RationalU256 {
    fn cmp(&self, other: &RationalU256) -> Ordering {
        let gcd = self.denom.gcd(&other.denom);
        let lhs = &self.numer * (&other.denom / &gcd);
        let rhs = &other.numer * (&self.denom / &gcd);
        lhs.cmp(&rhs)
    }
}