nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Complete number-theory reports reuse exact factorization and integer arithmetic.
use super::{bounded, decimal, err, factor_terms, factors, prime, value};
use crate::{Error, re};
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{One, Signed, Zero};

fn listed_divisors(factorization: &[(BigInt, u32)], squares_only: bool) -> Vec<BigInt> {
    let mut divisors = vec![BigInt::one()];
    for (prime, exponent) in factorization {
        let existing = divisors.clone();
        let mut power = BigInt::one();
        for step in 1..=*exponent {
            power *= prime;
            if !squares_only || step.is_multiple_of(2) {
                divisors.extend(existing.iter().map(|divisor| divisor * &power));
            }
        }
    }
    divisors.sort();
    divisors
}

pub(super) fn query(input: &str) -> Option<Result<String, Error>> {
    if let Some(c) = re!(r"^greatest common divisor and least common multiple of (.+?) and (.+?), then (add those two results|divide the larger result by the smaller)$").captures(input) {
        return Some((|| {
            let (a, b) = (value(&c[1])?, value(&c[2])?);
            let (gcd, lcm) = (a.gcd(&b), a.lcm(&b));
            let result = if &c[3] == "add those two results" {
                gcd + lcm
            } else {
                let (smaller, larger) = if gcd <= lcm { (gcd, lcm) } else { (lcm, gcd) };
                if smaller.is_zero() { return err("division_by_zero"); }
                larger / smaller
            };
            Ok(decimal(&result))
        })());
    }
    if let Some(c) = re!(r"^the smallest positive integer that leaves remainder (.+?) when / (.+)$")
        .captures(input)
    {
        return Some((|| {
            let remainder = value(&c[1])?;
            let divisors = c[2].replace(", and ", ", ").replace(" and ", ", ");
            let pieces = divisors.split(',').map(str::trim).collect::<Vec<_>>();
            if pieces.is_empty() || pieces.len() > 64 {
                return err("integer_limit");
            }
            if remainder.is_negative() {
                return err("invalid_integer_argument");
            }
            let mut period = BigInt::one();
            for divisor in pieces {
                let divisor = value(divisor)?;
                if divisor <= remainder {
                    return err("invalid_integer_argument");
                }
                period = period.lcm(&divisor);
                if period.bits() > 1_000_000 {
                    return err("integer_limit");
                }
            }
            // A shared nonzero residue itself is the minimum. A zero residue
            // requires the first positive member of the common-multiple class.
            Ok(decimal(&if remainder.is_zero() {
                period
            } else {
                remainder
            }))
        })());
    }
    if let Some(c) =
        re!(r"^list the positive divisors of (.+?) and tell me how many there are$").captures(input)
    {
        return Some((|| {
            let factorization = factors(&value(&c[1])?)?;
            let count: BigInt = factorization
                .iter()
                .map(|(_, exponent)| BigInt::from(exponent + 1))
                .product();
            // Complete terminal lists have at most 256 entries; scalar divisor
            // count requests retain their existing factorization limits.
            bounded(&count, 256)?;
            let divisors = listed_divisors(&factorization, false);
            Ok(format!(
                "divisors: {}; count: {}",
                divisors.iter().map(decimal).collect::<Vec<_>>().join(", "),
                decimal(&count)
            ))
        })());
    }
    if let Some(c) =
        re!(r"^all positive divisors of (.+?) that are perfect squares, and give their count$")
            .captures(input)
    {
        return Some((|| {
            let factorization = factors(&value(&c[1])?)?;
            let count: BigInt = factorization
                .iter()
                .map(|(_, exponent)| BigInt::from(exponent / 2 + 1))
                .product();
            // Bound the requested square subset, not the larger all-divisor set.
            bounded(&count, 256)?;
            let divisors = listed_divisors(&factorization, true);
            Ok(format!(
                "perfect-square divisors: {}; count: {}",
                divisors.iter().map(decimal).collect::<Vec<_>>().join(", "),
                decimal(&count)
            ))
        })());
    }
    if let Some(c) = re!(r"^is (.+?) prime, and what is its remainder when / (.+)$").captures(input)
    {
        return Some((|| {
            let (n, divisor) = (value(&c[1])?, value(&c[2])?);
            if divisor.is_zero() {
                return err("division_by_zero");
            }
            let primality = prime(&n)?;
            let remainder = value(&format!("({n}) mod ({divisor})"))?;
            Ok(format!(
                "prime: {primality}; remainder: {}",
                decimal(&remainder)
            ))
        })());
    }
    if let Some(c) = re!(
        r"^(?:prime factorization of (.+?) and use it to determine the number of positive factors|(.+?) as a product of primes and report the count of its positive divisors)$"
    )
    .captures(input)
    {
        return Some((|| {
            let n = value(c.get(1).or_else(|| c.get(2)).unwrap().as_str())?;
            let factorization = factors(&n)?;
            let count: BigInt = factorization
                .iter()
                .map(|(_, exponent)| BigInt::from(exponent + 1))
                .product();
            Ok(format!(
                "prime factorization: {}; positive {}: {}",
                factor_terms(&factorization).replace(" * ", " × "),
                if c.get(1).is_some() { "factors" } else { "divisors" },
                decimal(&count)
            ))
        })());
    }
    if let Some(c) = re!(r"^for (.+?) and (.+?), report their greatest common divisor, least common multiple, and simplified ratio$").captures(input) {
        return Some((|| {
            let (a, b) = (value(&c[1])?, value(&c[2])?);
            if b.is_zero() { return err("division_by_zero"); }
            let ratio = num_rational::BigRational::new(a.clone(), b.clone());
            Ok(format!("greatest common divisor: {}; least common multiple: {}; simplified ratio: {}:{}", decimal(&a.gcd(&b)), decimal(&a.lcm(&b)), decimal(ratio.numer()), decimal(ratio.denom())))
        })());
    }
    None
}