How do I work with very large integers (BigInteger) in EK9?

← Advanced Type System · Ref: Q1366

Integer in EK9 is 64-bit, and on overflow it becomes UNSET rather than wrapping. When you need whole numbers larger than that, use BigInteger - an arbitrary-precision integer that never overflows.

CREATING

  big <- BigInteger("123456789012345678901234567890")
  fromInt <- BigInteger(1000)     // widen from a 64-bit Integer

ARITHMETIC (NEVER OVERFLOWS)

+, -, * and ^ (power) grow the value as needed:

  squared <- big * big
  cubed <- big ^ 3

Comparisons (<, <=, >, >=, ==, <>, <=>), abs and sqrt are available too.

MOD AND REM

EK9 requires the mod and rem operators to return an Integer, so BigInteger.mod / .rem return a 64-bit Integer; if the result would not fit 64 bits it is returned UNSET rather than losing data.

NO PROMOTION TO FLOAT

BigInteger deliberately has NO #^ promote operator. A BigInteger is WIDER than a Float, so an implicit conversion would silently lose precision - exactly what BigInteger exists to avoid. If you really need a floating value, do the conversion explicitly.

DISPLAY

$ gives the full decimal string:

  stdout.println($big)

See Q1367 for exact decimals (BigDecimal). Use 'ek9 -h BigInteger' for the full API.

Example

defines module qa.biginteger.usage

  defines program

    BigIntegerUsage()
      stdout <- Stdout()

      //Arbitrary precision - multiplication never overflows.
      big <- BigInteger("123456789012345678901234567890")
      squared <- big * big
      stdout.println(`squared: ${squared}`)

      //Widen from a 64-bit Integer.
      fromInt <- BigInteger(1000)
      cubed <- fromInt ^ 3
      stdout.println(`cubed: ${cubed}`)
Other ways to ask this
  • What do I use when Integer overflows?
  • Is there arbitrary-precision integer arithmetic in EK9?
  • How do I compute large factorials or unbounded Fibonacci?

Coming from another language?

Java: java.math.BigInteger. Python: int is arbitrary precision by default. Go: math/big Int. Rust: num-bigint crate. EK9: BigInteger is built in; +,-,*,^ never overflow (contrast Integer which unsets on overflow); mod/rem return Integer (unset if out of 64-bit range); no #^ promote (a BigInteger is wider than Float).

Keywords: power, number, overflow, arbitrary, arithmetic, factorial, fibonacci, biginteger, precision, integer, large, big