diff --git a/src/fraction/frac.rs b/src/fraction/frac.rs new file mode 100644 index 0000000..08d6923 --- /dev/null +++ b/src/fraction/frac.rs @@ -0,0 +1,28 @@ +use std::ops::Add; + +#[derive(Clone, Debug)] +pub struct Frac{ + num: u32, + den: u32, +} + +impl Frac { + pub fn new(n: u32, d: u32) -> Self { + Frac { + num: n, + den: d, + } + } +} + + +impl Add for Frac { + type Output = Self; + + fn add(self, other: Self) -> Self { + Self { + num: self.num * other.den + other.num * self.den, + den: self.den * other.den, + } + } +} diff --git a/src/fraction/gcd.rs b/src/fraction/gcd.rs new file mode 100644 index 0000000..ea838b5 --- /dev/null +++ b/src/fraction/gcd.rs @@ -0,0 +1,20 @@ +pub fn gcd(mut a: u64, mut b: u64) -> u64 { + if a == 0 { return b } + if b == 0 { return a } + + let shift = (a | b).trailing_zeros(); + + a >>= a.trailing_zeros(); + + while b != 0 { + b >>= b.trailing_zeros(); + + if a > b { + core::mem::swap(&mut a, &mut b); + } + + b -= a; + } + + a << shift +} diff --git a/src/fraction/mod.rs b/src/fraction/mod.rs new file mode 100644 index 0000000..5e2d5dd --- /dev/null +++ b/src/fraction/mod.rs @@ -0,0 +1,4 @@ +mod frac; +pub use frac::*; +mod gcd; +pub use gcd::*; diff --git a/src/main.rs b/src/main.rs index e7a11a9..93fd50f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,12 @@ +mod fraction; +use fraction::Frac; + + fn main() { - println!("Hello, world!"); + let a = Frac::new(14, 200); + let b = Frac::new(1, 10); + + let c = a + b; + + println!("c = {:?}", c); }