module scheme import math import math.big import math.bits @[heap] struct BigInteger { value big.Integer } @[heap] struct BigRational { numerator big.Integer denominator big.Integer } fn (value Value) big_integer_pointer() &BigInteger { return unsafe { &BigInteger(value.pointer()) } } fn (value Value) big_rational_pointer() &BigRational { return unsafe { &BigRational(value.pointer()) } } @[inline] fn is_big_exact(value Value) bool { return value.tag in [.big_integer, .big_rational] } @[inline] fn is_exact_integer(value Value) bool { return value.tag in [.integer, .big_integer] } // No byte array, formatting, or private limb access is needed to narrow a big // result. get_bit reads two's complement; the complement keeps signed casts in range. fn big_i64(value big.Integer) ?i64 { if value.signum == 0 { return i64(0) } width := value.bit_len() if (value.signum > 0 && width > 63) || (value.signum < 0 && width > 64) { return none } mut raw := u64(0) for bit in 0 .. 64 { if value.get_bit(u32(bit)) { raw |= u64(1) << bit } } if value.signum < 0 { if raw >> 63 == 0 { return none } return -1 - i64(~raw) } return i64(raw) } // Internal immutable results can retain shared limbs. Box their header once. fn owned_big_integer(value big.Integer) Value { if small := big_i64(value) { return integer(small) } return payload_value(.big_integer, &BigInteger{ value: value }) } // integer_from_big snapshots the caller's limbs into the current allocator. // Like other host constructors, it must be called after popping a region when // the new value must outlive that region. Small results normalize inline. pub fn integer_from_big(value big.Integer) Value { if small := big_i64(value) { return integer(small) } return payload_value(.big_integer, &BigInteger{ value: value + big.zero_int }) } // rational_from_big snapshots retained caller storage and normalizes the ratio. pub fn rational_from_big(numerator big.Integer, denominator big.Integer) !Value { return normalize_big_rational(numerator, denominator, true) } // as_big_integer returns independent limbs in the currently active allocator. // Pop a host region before calling it to export a still-live Value from it. pub fn (value Value) as_big_integer() !big.Integer { if value.tag == .integer { return big.integer_from_i64(value.whole()) } if value.tag != .big_integer { return failure('expected an exact integer') } return value.big_integer_pointer().value + big.zero_int } // as_big_rational returns independent numerator/denominator limbs. Integers // have denominator one, matching as_rational's existing numeric contract. pub fn (value Value) as_big_rational() !(big.Integer, big.Integer) { match value.tag { .integer { return big.integer_from_i64(value.whole()), big.integer_from_int(1) } .rational { r := value.rational_pointer() return big.integer_from_i64(r.numerator), big.integer_from_i64(r.denominator) } .big_integer { return value.big_integer_pointer().value + big.zero_int, big.integer_from_int(1) } .big_rational { r := value.big_rational_pointer() return r.numerator + big.zero_int, r.denominator + big.zero_int } else { return failure('expected an exact number') } } } // Internal arithmetic borrows immutable headers, never clones a big input. fn big_integer_data(value Value) !big.Integer { if value.tag == .integer { return big.integer_from_i64(value.whole()) } if value.tag == .big_integer { return value.big_integer_pointer().value } return failure('expected an exact integer') } fn big_exact_parts(value Value) !(big.Integer, big.Integer) { match value.tag { .integer { return big.integer_from_i64(value.whole()), big.one_int } .big_integer { return value.big_integer_pointer().value, big.one_int } .rational { r := value.rational_pointer() return big.integer_from_i64(r.numerator), big.integer_from_i64(r.denominator) } .big_rational { r := value.big_rational_pointer() return r.numerator, r.denominator } else { return failure('expected an exact number') } } } fn exact_sign(value Value) int { return match value.tag { .integer { if value.whole() < 0 { -1 } else if value.whole() > 0 { 1 } else { 0 } } .rational { if value.rational_pointer().numerator < 0 { -1 } else { 1 } } .big_integer { value.big_integer_pointer().value.signum } .big_rational { value.big_rational_pointer().numerator.signum } else { 0 } } } fn big_quotient_exact(numerator big.Integer, divisor big.Integer) big.Integer { return if divisor == big.one_int { numerator } else { numerator / divisor } } fn big_product(a big.Integer, b big.Integer) big.Integer { if a == big.one_int { return b } if b == big.one_int { return a } return a * b } fn normalize_big_rational(numerator big.Integer, denominator big.Integer, copy bool) !Value { if denominator.signum == 0 { return failure('division by zero') } if numerator.signum == 0 { return integer(0) } g := big_gcd(numerator, denominator) return reduced_big_rational(big_quotient_exact(numerator, g), big_quotient_exact(denominator, g), copy && g == big.one_int) } // Arithmetic callers prove coprimality by cross-cancellation. A public // constructor copies only retained original limbs; reduced quotients own theirs. fn reduced_big_rational(numerator big.Integer, denominator big.Integer, copy bool) !Value { if denominator.signum == 0 { return failure('division by zero') } if numerator.signum == 0 { return integer(0) } if denominator.signum < 0 { return reduced_big_rational(big_neg_view(numerator), big_neg_view(denominator), copy) } if denominator == big.one_int { return if copy { integer_from_big(numerator) } else { owned_big_integer(numerator) } } if n := big_i64(numerator) { if d := big_i64(denominator) { return payload_value(.rational, &Rational{ numerator: n, denominator: d }) } } return payload_value(.big_rational, &BigRational{ numerator: if copy { numerator + big.zero_int } else { numerator } denominator: if copy { denominator + big.zero_int } else { denominator } }) } enum BigOperation { add subtract multiply divide } @[noinline] fn big_numeric_binary(a Value, b Value, operation BigOperation) !Value { if b.tag == .integer && b.whole() == 0 { if operation == .divide { return failure('division by zero') } return if operation == .multiply { integer(0) } else { a } } if a.tag == .integer && a.whole() == 0 { return match operation { .add { b } .subtract { numeric_negate(b)! } else { integer(0) } } } if b.tag == .integer && b.whole() == 1 && operation in [.multiply, .divide] { return a } if a.tag == .integer && a.whole() == 1 && operation == .multiply { return b } if b.tag == .integer && b.whole() == -1 && operation in [.multiply, .divide] { return numeric_negate(a) } if a.tag == .integer && a.whole() == -1 && operation == .multiply { return numeric_negate(b) } // Integer sums, differences and products need no rational reduction. // Borrow immutable inputs; the existing operators own the result's limbs. if operation != .divide && is_exact_integer(a) && is_exact_integer(b) { x, y := big_integer_data(a)!, big_integer_data(b)! if operation == .add { return owned_big_integer(x + y) } if operation == .subtract { return owned_big_integer(x - y) } return owned_big_integer(x * y) } an, ad := big_exact_parts(a)! bn, bd := big_exact_parts(b)! if operation in [.add, .subtract] { g := big_gcd(ad, bd) x := big_product(an, big_quotient_exact(bd, g)) y := big_product(bn, big_quotient_exact(ad, g)) n := if operation == .subtract { x - y } else { x + y } if n.signum == 0 { return integer(0) } h := big_gcd(n, g) d := big_product(big_quotient_exact(ad, g), big_quotient_exact(bd, h)) return reduced_big_rational(big_quotient_exact(n, h), d, false) } if operation == .multiply { g, h := big_gcd(an, bd), big_gcd(bn, ad) return reduced_big_rational(big_product(big_quotient_exact(an, g), big_quotient_exact(bn, h)), big_product(big_quotient_exact(ad, h), big_quotient_exact(bd, g)), false) } if bn.signum == 0 { return failure('division by zero') } g, h := big_gcd(an, bn), big_gcd(ad, bd) return reduced_big_rational(big_product(big_quotient_exact(an, g), big_quotient_exact(bd, h)), big_product(big_quotient_exact(ad, h), big_quotient_exact(bn, g)), false) } fn big_numeric_negate(value Value) !Value { n, d := big_exact_parts(value)! return reduced_big_rational(big_neg_view(n), d, false) } fn big_compare(a big.Integer, b big.Integer) int { return if a == b { 0 } else if a < b { -1 } else { 1 } } fn big_exact_compare(a Value, b Value) !int { // Canonical bignums lie strictly outside i64: comparing them with a small // integer needs neither promoted operands nor a temporary limb array. if a.tag == .big_integer && b.tag == .integer { return a.big_integer_pointer().value.signum } if a.tag == .integer && b.tag == .big_integer { return -b.big_integer_pointer().value.signum } an, ad := big_exact_parts(a)! bn, bd := big_exact_parts(b)! if an.signum != bn.signum { return if an.signum < bn.signum { -1 } else { 1 } } if ad == bd { return big_compare(an, bn) } return big_compare(big_product(an, bd), big_product(bn, ad)) } fn big_compare_real(value Value, floating f64) !int { if math.is_nan(floating) { return failure('cannot order NaN') } if math.is_inf(floating, 0) { return if floating > 0 { -1 } else { 1 } } return big_exact_compare(value, to_exact(real(floating))!) } // Bounded arithmetic signals overflow without constructing an error object. @[inline] fn small_add(a i64, b i64) ?i64 { if (b > 0 && a > exact_max - b) || (b < 0 && a < exact_min - b) { return none } return a + b } @[inline] fn small_subtract(a i64, b i64) ?i64 { if (b > 0 && a < exact_min + b) || (b < 0 && a > exact_max + b) { return none } return a - b } @[inline] fn small_multiply(a i64, b i64) ?i64 { // The existing wide-product API detects overflow without signed division. // magnitude handles exact_min without negating it in the signed domain. high, low := bits.mul_64(magnitude(a), magnitude(b)) negative := (a < 0) != (b < 0) limit := if negative { u64(1) << 63 } else { u64(exact_max) } if high != 0 || low > limit { return none } // Only a negative result can admit magnitude 2^63. Convert it explicitly // rather than casting that unsigned magnitude or negating exact_min. if low == u64(1) << 63 { return exact_min } return if negative { -i64(low) } else { i64(low) } } @[inline] fn integer_add_value(a Value, b Value, subtract bool) !Value { n := if subtract { small_subtract(a.whole(), b.whole()) } else { small_add(a.whole(), b.whole()) } if value := n { return integer(value) } return big_numeric_binary(a, b, if subtract { .subtract } else { .add }) } @[inline] fn integer_multiply_value(a Value, b Value) !Value { if value := small_multiply(a.whole(), b.whole()) { return integer(value) } return big_numeric_binary(a, b, .multiply) } fn is_integer_number(value Value) bool { return is_exact_integer(value) || (value.tag == .real && !math.is_inf(value.floating(), 0) && !math.is_nan(value.floating()) && math.floor(value.floating()) == value.floating()) } fn big_integer_division(p Primitive, a Value, b Value) !Value { if !is_integer_number(a) || !is_integer_number(b) { return failure('expected an integer') } inexact := a.tag == .real || b.tag == .real x, y := integer_value_big(a), integer_value_big(b) if y.signum == 0 { return failure('division by zero') } mut q, mut r := x.div_mod_checked(y)! if p in [.floor_quotient, .floor_divide, .modulo] && r.signum != 0 && r.signum != y.signum { q = q - big.one_int r = r + y } if inexact { if p in [.quotient, .floor_quotient] { return inexact_integer_result(q, negative_number(a) != negative_number(b)) } if p in [.remainder, .modulo] { return inexact_integer_result(r, negative_number(a)) } return numeric_values(inexact_integer_result(q, negative_number(a) != negative_number(b))!, inexact_integer_result(r, negative_number(a))!) } if p in [.quotient, .floor_quotient] { return owned_big_integer(q) } if p in [.remainder, .modulo] { return owned_big_integer(r) } return numeric_values(owned_big_integer(q), owned_big_integer(r)) } fn big_gcd_lcm(lcm bool, args []Value, inexact bool) !Value { mut result := if lcm { big.one_int } else { big.zero_int } for value in args { operand := integer_value_big(value) common := big_gcd(result, operand) result = if lcm { big_product(big_quotient_exact(result, common), operand) } else { common } if result.signum < 0 { result = big_neg_view(result) } } return if inexact { inexact_integer_result(result, false)! } else { owned_big_integer(result) } } fn big_rounded_number(p Primitive, value Value) !Value { if value.tag == .big_integer { return value } n, d := big_exact_parts(value)! mut q, r := n.div_mod_checked(d)! if p == .floor && r.signum < 0 { q = q - big.one_int } if p == .ceiling && r.signum > 0 { q = q + big.one_int } if p == .round && r.signum != 0 { complement := if r.signum < 0 { d + r } else { d - r } comparison := r.abs_cmp(complement) if comparison > 0 || (comparison == 0 && q.is_odd()) { q = if n.signum < 0 { q - big.one_int } else { q + big.one_int } } } return owned_big_integer(q) } fn big_integer_root(value Value) !Value { n := big_integer_data(value)! if n.signum < 0 { return failure('exact-integer-sqrt requires a nonnegative exact integer') } s := n.isqrt_checked()! return numeric_values(owned_big_integer(s), owned_big_integer(n - s * s)) } fn big_square_root(value Value) !Value { n, d := big_exact_parts(value)! nr, dr := n.isqrt_checked()!, d.isqrt_checked()! if nr * nr == n && dr * dr == d { return reduced_big_rational(nr, dr, false) } return real(math.sqrt(value.as_real()!)) } fn big_float_exact(significand u64, exponent int, negative bool) !Value { mut n := big.integer_from_u64(significand) mut d := big.one_int if exponent >= 0 { n = n.left_shift(u32(exponent)) } else { d = d.left_shift(u32(-exponent)) } if negative { n = big_neg_view(n) } return reduced_big_rational(n, d, false) } fn big_number_power(base Value, exponent Value) !Value { power := exponent.big_integer_pointer().value if base.tag == .real { x := base.floating() if x == 0 && power.signum < 0 { return failure('division by zero') } if x == 1 { return real(1) } if x == -1 { return real(if power.is_odd() { -1.0 } else { 1.0 }) } if x == 0 { return real(signed_zero(math.f64_bits(x) >> 63 != 0 && power.is_odd())) } return real(math.pow(x, exponent.as_real()!)) } if numeric_compare(base, integer(0))! == 0 { if power.signum < 0 { return failure('division by zero') } return integer(0) } if numeric_compare(base, integer(1))! == 0 { return integer(1) } if numeric_compare(base, integer(-1))! == 0 { return integer(if power.is_odd() { -1 } else { 1 }) } // Nontrivial powers beyond the signed-64-bit iteration range are an // explicit computation limit. Do not truncate the exponent to pow's u32 API. return failure('exact power exceeds supported computation range') } fn big_simplest_positive(lower Value, upper Value) !Value { mut low, mut high := lower, upper mut a, mut b, mut c, mut d := integer(1), integer(0), integer(0), integer(1) for { q := rounded_number(.floor, low)! mut terminal := numeric_compare(low, q)! == 0 mut result := q if !terminal && numeric_compare(q, rounded_number(.floor, high)!)! < 0 { result = numeric_add(q, integer(1))! terminal = true } if terminal { return numeric_divide(numeric_add(numeric_multiply(a, result)!, b)!, numeric_add(numeric_multiply(c, result)!, d)!) } next_a := numeric_add(numeric_multiply(a, q)!, b)! next_c := numeric_add(numeric_multiply(c, q)!, d)! b, d = a, c a, c = next_a, next_c next_low := numeric_divide(integer(1), numeric_subtract(high, q)!)! high = numeric_divide(integer(1), numeric_subtract(low, q)!)! low = next_low } return unspecified() } // Public Integer value updates share its immutable backing storage without // reaching into private limbs. Only internal views use this; host exports copy. fn big_abs_view(value big.Integer) big.Integer { return if value.signum < 0 { big.Integer{ ...value, signum: -value.signum } } else { value } } fn big_neg_view(value big.Integer) big.Integer { return big.Integer{ ...value, signum: -value.signum } } fn big_gcd(a big.Integer, b big.Integer) big.Integer { if a.signum == 0 { return big_abs_view(b) } if b.signum == 0 { return big_abs_view(a) } left, right := big_abs_view(a), big_abs_view(b) if left == big.one_int || right == big.one_int { return big.one_int } return left.gcd(right) }