diff options
Diffstat (limited to 'src/utils.rs')
-rw-r--r-- | src/utils.rs | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..c53b959 --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,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} +} |