Functional Weave
Code in Python

math.gcd-lcm@2.0.0

impl/rust/lcm.rs

1,061 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::math_gcd_lcm_gcd::gcd;  ← gcd, another function of this group · built into the same file, even by a slim install

/// Least common multiple, never negative; 0 when either input is 0.
///
/// # Panics
/// Panics if either input is outside ±(2^53 - 1), or the lcm is.
pub fn lcm(a: i64, b: i64) -> i64 {
    let g = gcd(a, b);
    if g == 0 {
        return 0;
    }
    // Divide before multiplying: a * b overflows long before the lcm does.
    let result = (a as i128).abs() / (g as i128) * (b as i128).abs();
    if result > 9_007_199_254_740_991 {
        panic!("the lcm of {} and {} exceeds 2^53 - 1", a, b);
    }
    result as i64
}

// Refuse what the typed signature cannot hold, with the wording TypeScript
// and Python use, rather than let the conversion quietly truncate it.
fn int_arg(v: &Value, name: &str) -> i64 {
    if let Value::Float(f) = v {
        if f.fract() != 0.0 {
            panic!("{} must be an integer, received {}", name, f);
        }
    }
    v.as_i64()
}

pub fn fune_vector(args: &[Value]) -> Value {
    Value::Int(lcm(int_arg(&args[0], "a"), int_arg(&args[1], "b")))
}