aboutsummaryrefslogtreecommitdiff
path: root/src/utils.rs
blob: c53b9594ed9528640d705cbb410dd79b899117fc (plain) (blame)
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
pub struct Rational
{
    n: i64,
    d: i64
}

fn gcd(a: i64, b: i64) -> i64
{if b != 0 { gcd(b, a % b) } else { a }}

impl Default for Rational
{
    fn default() -> Rational { Rational::from_int(0) }
}

impl Rational
{
    fn from_int(v: i64) -> Rational {Rational{n: v, d: 1}}
    fn reduced(self) -> Rational
    {
        let c = gcd(self.n, self.d);
        Rational{n: self.n / c, d: self.d / c}
    }
    fn add(self, other: Rational) -> Rational
    {
        let c = gcd(self.d, other.d);
        Rational{n: self.n * (other.d / c) + other.n * (self.d / c),
                 d: self.d / c * other.d}.reduced()
    }
    fn multiply(self, other: Rational) -> Rational
    {
        Rational{n: self.n * other.n, d: self.d * other.d}.reduced()
    }
    fn as_int_trunc(self) -> i64 {self.n / self.d}
    fn as_int_round(self) -> i64 {(self.n as f64 / self.d as f64).round() as i64}
}