Whole numbers of unlimited size: large factorials, cryptography, and any arithmetic that will not fit in 64 bits.
import bigint
An i64 stops at about 9.2 × 10^18 and wraps around without warning. bigint.Int is a whole number whose size is limited only by memory: use it for factorials and combinatorics, exact counters that can grow without bound, token amounts in their smallest unit, and number theory such as modular exponentiation. For money with a fixed number of decimal places use decimal, and for real keys and signatures use crypto.
A number is a sign and a vector of 32-bit limbs. Multiplication is the schoolbook method and conversion to text divides repeatedly, so numbers of a few thousand digits are quick and numbers of a million digits are slow.
Most functions return a new number and leave their arguments alone. The ones whose names end in To, From or By, such as AddTo, store the result in their first argument and free its old value for you. They still allocate the new value, so they are not faster; what they save is the bookkeeping of freeing every intermediate result. Release a number you no longer need with Free.
What people get wrong:
•
Copying with =. b := a copies only the header, so both names share one set of limbs, and the next in-place call on b frees the memory a still points to. Use Clone for a second, independent number.
•
Dividing by zero. Div, Rem, Mod and ModExp do not stop the program; they return 0. When the divisor can be zero, use DivMod, which returns false.
•
Expecting an error for impossible input. A negative exponent in Pow, the square root of a negative number and the factorial of a negative number all return 0, and ToStrBase with a base outside 2 to 36 returns empty text.
Past the end of i64
The 93rd Fibonacci number is the first one that does not fit in an i64; with ordinary integers it would wrap around to a negative value without warning. With bigint.Int the loop just keeps going. ToInt converts back and tells you, through its bool argument, whether the value fitted, so you can move to plain integers when the numbers are small again.
bigint-guide-fibonacci.salam
import bigint
importstrfuncmain:
mut a := bigint.Zero()
mut b := bigint.One()
repeat1to300in n:
next := bigint.Add(a, b)
bigint.Free(a)
a = b
b = next
if n == 92or n == 93:
mut fits := false
v := bigint.ToInt(a, fits)
println"F(" + str.FromInt(n) + ") =", bigint.ToStr(a), "fits in i64:", fits, v
endend
text := bigint.ToStr(a)
println"F(300) has", text.Len(), "digits"println text
bigint.Free(a)
bigint.Free(b)
end
Output
F(92) = 7540113804746346429 fits in i64: true 7540113804746346429
F(93) = 12200160415121876738 fits in i64: false 0
F(300) has 63 digits
222232244629420445529739893461909967206666939096499764990979600
Each Add returns a new number, so the loop frees the value it no longer needs before it moves the names along. Without the Free calls the program would still be correct, but it would keep every intermediate number in memory.
Updating one number in a loop
A loop that updates one number with Add has to free the old value on every step, as the Fibonacci loop above does. MulIntBy, AddTo, ShlBy and the other functions named with To, From or By do that for you: they put the result into their first argument and free what was there. Build the result in one variable and free it once at the end.
50! = 30414093201713378043612608166064768844377641568960512000000000000
same as Factorial(50): true
1 + 2 + 4 + ... + 2^63 = 18446744073709551615
that is 2^64 - 1: true
Copies and snapshots
To keep an old value while you change the number, take a copy with Clone. A plain opening := balance would not work: both names would share the same limbs, and the first AddIntTo would free them under opening, which then prints garbage. Each clone is its own allocation and needs its own Free.
ToStr gives the decimal text, so its length is the number of digits. DivModInt divides by an ordinary integer and puts the remainder into an i64, which is the way to walk through the digits one by one, here to add them up. TrailingZeros counts zero bits, not decimal zeros.
bigint-guide-digits.salam
import bigint
funcdigit_sum(x: bigint.Int): i64:
mut rest := bigint.Clone(x)
defer bigint.Free(rest)
mut sum := 0asi64until bigint.IsZero(rest) == false:
mut d := 0asi64
q := bigint.DivModInt(rest, 10, d)
bigint.Free(rest)
rest = q
sum += d
endret sum
endfuncmain:
mut p := bigint.Pow(bigint.FromInt(2), 1000)
mut f := bigint.Factorial(100)
defer bigint.Free(p)
defer bigint.Free(f)
println"2^1000 has", bigint.ToStr(p).Len(), "digits, digit sum", digit_sum(p)
println"100! has", bigint.ToStr(f).Len(), "digits, digit sum", digit_sum(f)
println"100! ends in", bigint.TrailingZeros(f), "zero bits"end
Output
2^1000 has 302 digits, digit sum 1366
100! has 158 digits, digit sum 648
100! ends in 97 zero bits
Reading and printing in other bases
Parse reads decimal text and reports through its bool argument whether the text was a whole number; an empty string, a stray letter or a trailing space fails. Leading spaces, a sign, Persian digits and _ between digits (1_000_000) are accepted. With base 0, ParseBase reads a 0x, 0b or 0o prefix and falls back to decimal. ParseBase and ToStrBase handle bases from 2 to 36, and ToHex is the usual form for keys and hashes. ToIntClamped gives the largest or smallest i64 when the value is out of range.
bigint-guide-parse.salam
import bigint
funcmain:
inputs := ["340282366920938463463374607431768211455", "-12345678901234567890", "12a4", ""]
each s in inputs:
mut ok := falsemut n := bigint.Parse(s, ok)
if ok:
println s, "->", bigint.BitLen(n), "bits, sign", bigint.Sign(n)
else:
println"[" + s + "] is not a whole number"end
bigint.Free(n)
endmut ok := falsemut key := bigint.ParseBase("deadbeefcafebabe0123456789", 16, ok)
println ok, bigint.ToStr(key)
println"base 36:", bigint.ToStrBase(key, 36)
println"back to hex:", bigint.ToHex(key)
println"clamped to i64:", bigint.ToIntClamped(key)
bigint.Free(key)
end
Output
340282366920938463463374607431768211455 -> 128 bits, sign 1
-12345678901234567890 -> 64 bits, sign -1
[12a4] is not a whole number
[] is not a whole number
true 17642423813161689323077271644041
base 36: 1biglrj84lzg25oox7rex
back to hex: deadbeefcafebabe0123456789
clamped to i64: 9223372036854775807
Division, remainders and zero
There are three ways to divide, and they differ only for negative numbers. Div and Rem round towards zero, as C and Go do. FloorDiv and FloorMod round down, as Python does, so the remainder takes the sign of the divisor. Mod and ModInt always give a remainder from 0 up to the divisor, which is what modular arithmetic and a day-of-week calculation want. DivMod gives the quotient and the remainder from one division, and its bool is the only way to notice a zero divisor.
bigint-guide-division.salam
import bigint
funcshow(label: str, x: bigint.Int):
println label, bigint.ToStr(x)
endfuncmain:
mut ok := falsemut pool := bigint.Parse("1_250_000_000_000_000_000_000", ok)
defer bigint.Free(pool)
mut winners := bigint.FromInt(7)
defer bigint.Free(winners)
mut share := bigint.Zero()
mut dust := bigint.Zero()
defer bigint.Free(share)
defer bigint.Free(dust)
if bigint.DivMod(pool, winners, share, dust):
show("each winner gets:", share)
show("left in the pool:", dust)
endmut nobody := bigint.Zero()
defer bigint.Free(nobody)
if bigint.DivMod(pool, nobody, share, dust) == false:
println"no winners: DivMod returned false"endmut silent := bigint.Div(pool, nobody)
defer bigint.Free(silent)
show("Div by zero quietly gives", silent)
mut debt := bigint.FromInt(-10)
mut days := bigint.FromInt(3)
defer bigint.Free(debt)
defer bigint.Free(days)
mut t := bigint.Div(debt, days)
mut m := bigint.Rem(debt, days)
println"Div, Rem:", bigint.ToStr(t), bigint.ToStr(m)
bigint.Free(t)
bigint.Free(m)
t = bigint.FloorDiv(debt, days)
m = bigint.FloorMod(debt, days)
println"FloorDiv, FloorMod:", bigint.ToStr(t), bigint.ToStr(m)
bigint.Free(t)
bigint.Free(m)
println"ModInt:", bigint.ModInt(debt, 3)
end
Output
each winner gets: 178571428571428571428
left in the pool: 4
no winners: DivMod returned false
Div by zero quietly gives 0
Div, Rem: -3 -1
FloorDiv, FloorMod: -4 2
ModInt: 2
Modular arithmetic: a toy RSA
Public key cryptography is built on ModExp, ModInverse and Gcd. The program below makes an RSA key from two small primes, encrypts a number with the public exponent and decrypts it with the private one. ModInverse fails, through its bool, when the two numbers share a factor.
bigint-guide-rsa.salam
import bigint
funcmain:
p := bigint.FromInt(1000000007)
q := bigint.FromInt(998244353)
n := bigint.Mul(p, q)
phi := bigint.Mul(bigint.SubInt(p, 1), bigint.SubInt(q, 1))
e := bigint.FromInt(65537)
println"public key n:", bigint.ToStr(n), "e:", bigint.ToStr(e)
println"gcd(e, phi):", bigint.ToStr(bigint.Gcd(e, phi))
mut ok := false
d := bigint.ModInverse(e, phi, ok)
ifnot ok:
println"e has no inverse, pick another e"ret1endprintln"private exponent d:", bigint.ToStr(d)
message := bigint.FromInt(424242424242)
secret := bigint.ModExp(message, e, n)
back := bigint.ModExp(secret, d, n)
println"message: ", bigint.ToStr(message)
println"encrypted:", bigint.ToStr(secret)
println"decrypted:", bigint.ToStr(back)
println"round trip:", bigint.Equals(message, back)
ret0end
This is for learning how the arithmetic works. Real RSA needs primes of more than a thousand bits, random padding and constant time code; for real keys and signatures use crypto.
Turns decimal text into a big number. Leading spaces, a sign, Persian or Arabic digits and _ between digits are accepted. When the text is not a valid number, ok turns false and the result is 0.
The example for this item is shown with the ones above: bigint-Parse.salam
Computes base to the power e modulo m without building the huge intermediate number; the basis of RSA. The result is from 0 to |m|-1. A zero m or a negative e gives 0.
bigint-ModExp.salam
import bigint
funcmain:
println bigint.ToStr(bigint.Factorial(30))
println bigint.ToStr(bigint.ModExp(bigint.FromInt(4), bigint.FromInt(13), bigint.FromInt(497)))
println bigint.ToStr(bigint.Gcd(bigint.FromInt(48), bigint.FromInt(18))),
bigint.ToStr(bigint.Lcm(bigint.FromInt(4), bigint.FromInt(6)))
mut x := bigint.Zero()
mut y := bigint.Zero()
g := bigint.ExtGcd(bigint.FromInt(240), bigint.FromInt(46), x, y)
println bigint.ToStr(g), bigint.ToStr(x), bigint.ToStr(y)
mut ok := false
inv := bigint.ModInverse(bigint.FromInt(3), bigint.FromInt(11), ok)
println ok, bigint.ToStr(inv)
println bigint.ToStr(bigint.Sqrt(bigint.Pow10(20)))
end