Skip to content

Commit

Permalink
add gcd() function
Browse files Browse the repository at this point in the history
  • Loading branch information
funnyboy-roks committed Oct 26, 2023
1 parent 9d74e30 commit 9467f4b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
23 changes: 23 additions & 0 deletions src/ast/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,28 @@ pub fn default_functions() -> FnMap {
def_fn!(round);
def_fn!(abs);

def_fn!(
gcd = |expr, args| {
let mut args = args.iter().map(|a| expr.eval(a));
let mut r = args.next().unwrap()?;
for n in args {
r = gcd(r, n?);
}
Ok(r)
}
);

map
}

fn gcd(mut a: f64, mut b: f64) -> f64 {
if a == 0.0 {
return b;
}
while b > 0.0 {
let r = a % b;
a = b;
b = r;
}
return a;
}
8 changes: 7 additions & 1 deletion src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,13 @@ fn functions() {

test_fn!(
log_7(expr!(num!(7.0), op!(Exponent), num!(6.0))),
"log_7(7 ** 6)", // TODO: fractions in input
"log_7(7 ** 6)",
6.0
);

test_fn!(
gcd(expr!(num!(3.0)), expr!(num!(6.0)), expr!(num!(54.0))),
"gcd(3, 6, 54)",
3.0
);
}

0 comments on commit 9467f4b

Please sign in to comment.