Skip to content

Commit

Permalink
Implement LCM function
Browse files Browse the repository at this point in the history
  • Loading branch information
kdkasad committed Apr 1, 2024
1 parent 6d16096 commit ff0cfd6
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ pub enum Function {
/// ## Greatest common denominator
#[strum(serialize = "gcd")]
GCD,

/// ## Least common multiple
#[strum(serialize = "lcm")]
LCM,
}

impl Function {
Expand All @@ -73,7 +77,7 @@ impl Function {
use Function::*;
match self {
Sine | Cosine | AbsoluteValue | SquareRoot | NaturalLogarithm => 1,
GCD => 2,
GCD | LCM => 2,
}
}

Expand All @@ -93,13 +97,19 @@ impl Function {
args.len(),
));
}
macro_rules! arg {
() => {
args.pop().unwrap()
};
}
Ok(match self {
Sine => sin(args.swap_remove(0))?,
Cosine => cos(args.swap_remove(0))?,
AbsoluteValue => abs(args.swap_remove(0)),
SquareRoot => sqrt(args.swap_remove(0))?,
NaturalLogarithm => ln(args.swap_remove(0))?,
GCD => gcd(args.swap_remove(0), args.swap_remove(0))?,
Sine => sin(arg!())?,
Cosine => cos(arg!())?,
AbsoluteValue => abs(arg!()),
SquareRoot => sqrt(arg!())?,
NaturalLogarithm => ln(arg!())?,
GCD => gcd(arg!(), arg!())?,
LCM => lcm(arg!(), arg!())?,
}
.into())
}
Expand Down Expand Up @@ -187,6 +197,10 @@ fn gcd(a: BigRational, b: BigRational) -> Result<BigRational, EvalError> {
Ok(x.into())
}

fn lcm(a: BigRational, b: BigRational) -> Result<BigRational, EvalError> {
Ok(&a * &b / gcd(a, b)?)
}

#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
Expand Down

0 comments on commit ff0cfd6

Please sign in to comment.