|
Big Integers: Exact to the Last Digit for Number Theory and Cryptography |
Sheerpower's REAL type is built for business numbers: prices, quantities, rates and totals. A REAL holds 54 digits before the decimal point and 16 after. It is fast, because many ordinary operations run as native 64-bit integer instructions.
Past that range, a REAL switches to scientific notation and keeps 64 significant digits. That is far more than any ledger needs, but it is not enough for number theory.
Take a 2048-bit RSA key. Its modulus is 617 digits long. A primality test on a number that size depends on the last digit as much as the first. A REAL would keep the leading 64 digits and round the rest away.
Big integers fill that gap. A big integer is a whole number held as a string of digits, up to one billion digits long. Every operation on it is exact, down to the final digit.
The trade-off is speed and storage. A big integer takes more room as its value grows, and math takes longer as the digits grow. So use a REAL for an invoice total. Use a big integer for primes, cryptographic keys, exact factorials, and any very large integers whose last digits carry the meaning.
Here is the difference: sixty factorial (60 × 59 × ... × 1, the number of ways to line up sixty people), worked out both ways.
Output:
The true value has 82 digits. The REAL keeps the first 64, and the rounding of the last few multiplies has reached even those: its 64th digit is a 4 where the true digit is a 6. The big integer has every digit.
There is no new type to learn. A big integer is an
ordinary string of digits, so it prints, goes into a cluster or a table
field, is written to a file, and goes straight back into the next call.
The functions take strings of digits or whole numbers, and give back a
string: a minus sign first when it is negative, no leading zeros, and
'0' for zero. BIGCMP() and ISPRIME()
answer with a number instead.
Sixteen functions do the arithmetic, eleven more work on the bits and write numbers in other bases, one groups a number's digits for reading, and three more test and find primes. Each has its own entry, with more examples, on the String Manipulation Functions and Features page.
| Function | What it gives | Example | Answer |
|---|---|---|---|
BIGADD$(a, b) | a + b | bigadd$('99999999999999999999', 1) | 100000000000000000000 |
BIGSUB$(a, b) | a − b | bigsub$(5, 7) | -2 |
BIGMUL$(a, b) | a × b | bigmul$('99999999999', '99999999999') | 9999999999800000000001 |
BIGPOW$(base, exponent) | baseexponent | bigpow$(2, 100) | 1267650600228229401496703205376 |
BIGDIV$(a, b) | a ÷ b with the fraction dropped, as INT() drops it; the remainder goes into _string$ | bigdiv$('100', '7') | 14, and _string$ is 2 |
BIGMOD$(a, b) | a modulo b, with the sign of b, as MOD() gives it | bigmod$('-7', '3') | 2 |
BIGSQRT$(n) | the square root, rounded down; the remainder goes into _string$ | bigsqrt$(99) | 9, and _string$ is 18 |
BIGROOT$(n, k) | the k-th root with the fraction dropped toward zero; the remainder goes into _string$ | bigroot$(1000, 3) | 10, and _string$ is 0 |
BIGFAC$(n [, k]) | n!, or the ways to choose k things from n, the order not counting | bigfac$(52, 5) | 2598960 |
BIGCMP(a, b) | −1, 0 or 1: a is smaller, equal or larger | bigcmp('9', '10') | -1 |
BIGPOWMOD$(base, exponent, modulus [, constant_time: true]) | baseexponent modulo modulus, without ever making the power itself; constant_time: true for a secret exponent | bigpowmod$('4', '13', '497') | 445 |
BIGINVMOD$(value, modulus) | the inverse: the x for which value × x modulo modulus is 1 | biginvmod$('3', '11') | 4 |
BIGGCD$(a, b) | the greatest common divisor: the largest number that divides both, never negative | biggcd$('12', '18') | 6 |
BIGLCM$(a, b) | the least common multiple: the smallest number that both divide | biglcm$('4', '6') | 12 |
BIGJACOBI(a, n) | the Jacobi symbol: −1, 0 or 1; n odd and above 0 | bigjacobi(2, 7) | 1 |
BIGSQRTMOD$(a, p) | the smaller x with x × x modulo the prime p equal to a | bigsqrtmod$(2, 7) | 3 |
BIGRAND$(low, high) | a random whole number from low to high, both included | bigrand$(7, 7) | 7 |
BIGAND$(a, b), BIGOR$(a, b), BIGXOR$(a, b) | a and, or, xor b, bit by bit; a negative number in two's complement | bigand$(12, 10) | 8 |
BIGNOT$(n) | every bit turned over: −n − 1 | bignot$(5) | -6 |
BIGSHL$(n, k), BIGSHR$(n, k) | n × 2k; n ÷ 2k rounded down | bigshr$(-5, 1) | -3 |
BIGTESTBIT(n, k), BIGSETBIT$(n, k, bit) | bit k, 0 or 1; n with bit k made 0 or 1 | bigsetbit$(0, 100, 1) | 1267650600228229401496703205376 |
BIGBITLEN(n) | the bits n needs, its sign ignored | bigbitlen(255) | 8 |
BIGTOBASE$(n, base [, width]) | n in base 2 to 36, lowercase, or as bytes (base 256) | bigtobase$(255, 16) | ff |
BIGFROMBASE$(text, base) | the number text holds in base 2 to 36 or 256, as digits | bigfrombase$('0xFF', 16) | 255 |
BIGFORMAT$(n [, separator [, group]] [, last: count]) | n's digits grouped for reading: a comma between each three, or any separator and group; last: count shows only the last digits | bigformat$('1234567') | 1,234,567 |
ISPRIME(n) | 1 when n is prime, otherwise 0; a string of up to 2,500 digits | isprime('2305843009213693951') | 1 |
NEXTPRIME$(n [, offset]) | the first prime past n, as digits; up to 2,500 digits | nextprime$('1000000000000000000000') | 1000000000000000000117 |
PREVPRIME$(n [, offset]) | the largest prime below n, as digits; up to 2,500 digits | prevprime$(100) | 97 |
An argument is a whole number, or its digits as a string. In a string,
commas, underscores, spaces, line breaks and every other character up to the
space are skipped, so the digits may be grouped for reading —
'1,000,000', '1_000_000', '1 000 000'
— or broken over lines; a + or − sign may come first, and leading
zeros are fine. A REAL that holds a whole number works too, and
val() turns an answer of up to 64 digits back into a REAL:
Output:
BIGFORMAT$() goes the other way: it groups an answer's digits for
reading, a comma between each three by default, or any separator and any
group size. The comma, underscore and space forms read straight back in:
Output:
With last: it shows only an answer's last digits, grouped as they
are in the whole number, and any zeros they begin with are kept. It suits an
answer too long to print: only those digits are copied.
Output:
A REAL keeps 64 significant digits, so a bigger whole number worked out as a REAL has lost its last digits before any big-integer function sees it. The compiler refuses a number written in the program with more than 64 digits (“Number has more digits than can be held exactly”), but a REAL worked out as the program runs is rounded without a word:
Output:
10100 + 1 has 101 digits. As a REAL the + 1 was rounded away,
so its last digit is 0; built from digits, it is 1. Build big numbers with
the functions, or from text: a file, a form, repeat$().
< and > compare two strings as text, and as
text '9' comes after '10'. An answer never has
leading zeros, so = between two answers is safe, but digits
typed in may not be: '007' and '7' are different
strings. BIGCMP() compares the numbers:
Output:
Sharing out, with a remainder. BIGDIV$()
gives the quotient and puts the remainder in _string$. Read it
straight after the call: other functions and every exception set
_string$ too. The quotient times the divisor, plus the
remainder, is always the number divided:
Output:
The digits of 21000. BIGPOW$()
raises a number to a power. 21000 is 302 digits long; here are
its digits added up:
Output:
Common factors. BIGGCD$() finds the largest
number that divides two others, and BIGLCM$() the smallest
number that both divide. A fraction comes down to its lowest terms by
dividing top and bottom by their greatest common divisor: here 50! over
260, which share 247.
Output:
And the smallest number that every whole number from 1 to 100 divides, one least common multiple at a time:
Output:
Roots. BIGSQRT$() and BIGROOT$()
give a root with its fraction dropped and put the remainder in
_string$, as BIGDIV$() does, so an exact power
leaves a remainder of 0. The root of a number scaled up by a power of ten
gives its digits past the point: here the square root of 2 to 50 places,
from the root of 2 × 10100.
Output:
Give ISPRIME() a big number's digits as a string, up to 2,500
digits. Above about 3.3 × 1024 it runs the
Baillie–PSW test, and no composite number is known that passes it. A
Mersenne number is one less than a power of 2. These are the exponents up
to 1,300 that make one prime; the last, 21279 − 1, has 386
digits, and the whole search takes a fraction of a second:
Output:
NEXTPRIME$() returns the first prime past a number, as digits.
Given its own answer back, it walks from prime to prime. The first three
primes past 1050:
Output:
PREVPRIME$() searches the other way, for the largest prime below
a number, and BIGRAND$() draws a starting point from the system's
random source: a random 100-digit prime is the next prime past a random
100-digit number.
Output:
A puzzle from the Chinese mathematics book Sunzi Suanjing, written
between the 3rd and 5th centuries: a number leaves 2 when divided by 3, 3
when divided by 5, and 2 when divided by 7. What is it? The answer is
built from modular inverses. The same loop works with moduli hundreds of
digits long, as long as no two of them share a factor — BIGGCD$() of each pair is '1' (if two do share one,
BIGINVMOD$() raises NOINVERSE):
Output:
Quadratic residues. BIGJACOBI() gives the Jacobi
symbol: for a prime p it is 1 when a has a square root modulo p, −1 when
it has none, and 0 when p divides a. BIGSQRTMOD$() finds the root
— the smaller of the two — squares it back before giving it, and
raises NOSQRTMOD when there is none. Here the modulus is the
largest prime below 2255:
Output:
Public-key cryptography is modular arithmetic on big whole numbers, and two
functions do nearly all of it. BIGPOWMOD$() raises a number to
a power modulo another without ever making the power: a 600-digit number to
a 600-digit power would have more digits than there are atoms in the
universe. BIGINVMOD$() finds an inverse.
RSA, start to finish. Two primes make the key: their
product is the public modulus, and the private exponent is the inverse of
the public one modulo (p − 1)(q − 1), which exists because 65537
shares no factor with it: biggcd$(public_exp$, totient$) is '1'. Anyone can encrypt with
the public pair; only the private exponent decrypts. Signing is the same
two calls the other way round, and each call with a secret exponent adds constant_time: true (the note below says why). The message must be a number smaller than
the modulus, so this 100-digit modulus carries up to 33 characters:
Output:
Diffie–Hellman key agreement. Alice and Bob agree on a prime and a base in public. Each picks a secret, sends the base to the power of that secret, and raises what the other sent to their own secret. Both arrive at the same key, though neither secret ever crossed the wire:
Output:
These show the arithmetic, not a finished security system.
Real keys start from cryptographically random digits (BIGRAND$()
draws them from the system's random source, as Random Byte Generator for Cryptographic Use does), and
use bigger numbers: two primes of 309 digits for
a 2048-bit RSA key, and a prime of 617 digits or more, chosen with care,
for a key exchange. Real RSA messages and signatures need padding, which
these examples leave out. A plain BIGPOWMOD$()'s time depends
on the exponent's bits; with constant_time: true the same steps
run and the same memory is read whatever they are. It needs an odd modulus,
as RSA and Diffie–Hellman moduli are, and it guards the exponent's bits
only: the exponent's size still shows, and the base, the modulus and the
answer are handled by the ordinary code. It takes 10 to 15 percent longer.
Eleven functions work on a number's bits and write it in other bases.
BIGAND$(), BIGOR$(), BIGXOR$() and
BIGNOT$() combine bits; BIGSHL$() and
BIGSHR$() move them; BIGTESTBIT(),
BIGSETBIT$() and BIGBITLEN() read one, set one and
count them. A negative number is read in two's complement with its sign bit
repeated for ever, as Python, Java and GMP read it: −1 is all ones,
bignot$(x) is −x − 1, and a right shift rounds down,
so bigshr$(-5, 1) is −3.
BIGTOBASE$() writes a number in base 2 to 36, lowercase, or in
base 256: its bytes, the big end first, as keys and hashes are stored.
BIGFROMBASE$() reads either back, letters in either case, an
optional 0x, 0o or 0b after any sign,
and spaces, commas and underscores skipped. Here a SHA-256 digest becomes a
number, a 2048-bit key becomes exactly 256 bytes, and flags 201 bits wide are
built and tested:
Output:
The bit functions and the bases turn a number into binary and back, so they cost more than an add: numbers of a few hundred digits take microseconds, a million-digit number a second or more. A shift, a bit test and the bit length need no conversion.
A mistake raises an exception you can catch, and _string$ says
which function and what was wrong:
| Exception | Raised by |
|---|---|
ILLARGBIG | a string that is not a whole number in digits, a number with a fraction, a negative exponent or modulus, a root below 1, or an even root of a negative number; for the bits and bases, a negative bit number, shift or width, a bit other than 0 or 1, a base other than 2 to 36 or 256, a negative number in base 256, an answer wider than its width, or text that is not a whole number in its base; an even or negative n for BIGJACOBI(), a high below the low for BIGRAND$(), a modulus BIGSQRTMOD$() finds is not a prime; an even modulus with constant_time: true for BIGPOWMOD$(), a group below 1 for BIGFORMAT$() |
BIGTOOLONG | an argument or an answer of more than 1,000,000,000 digits (characters, for BIGTOBASE$() and BIGFORMAT$()) — a loop that grows a number can catch it by name, exceptiontype('bigtoolong'), and stop cleanly |
DIVBY0 | a divisor or a modulus of 0 |
NOINVERSE | BIGINVMOD$() given a value and a modulus that share a factor |
NOSQRTMOD | BIGSQRTMOD$() given a value with no square root modulo the prime |
ILLARGISPRIME, ILLARGNEXTPRIME, ILLARGPREVPRIME | ISPRIME(), NEXTPRIME$() or PREVPRIME$() given a string that is not a whole number in digits, or more than 2,500 digits; PREVPRIME$() also a number below 2 |
Output:
No message in _string$ shows an argument's digits, because they
are often keys. BIGPOWMOD$() and BIGINVMOD$() name
the argument by its role, as above, and the other functions by its place:
bigadd$(): the first number must be a whole number in digits.
None of these functions is worked out while the program compiles, even
when every argument is a constant, so a long calculation never holds up a
compile: a bad constant raises its exception when the call runs.
An add takes longer as the digits grow, and a multiply grows faster than that. Measured on a laptop with an Intel Core i5-12450H:
| Work | Speed |
|---|---|
bigadd$() of two 100-digit numbers | about 1 million a second |
bigmul$() of two 100-digit numbers | about 750,000 a second |
bigmul$() of two 1,000-digit numbers | about 35,000 a second |
bigmul$() of two 10,000-digit numbers | about 1,000 a second |
bigdiv$() of 2,000 digits by 1,000 digits | about 10,000 a second |
isprime() of a 100-digit prime | about 6,000 a second |
isprime() of a 617-digit prime | about 110 a second |
nextprime$() from a 309-digit start: one prime of a 2048-bit RSA key | about 100 a second |
bigpowmod$() with a 617-digit exponent and modulus: one 2048-bit RSA private-key step | about 180 a second |
biginvmod$() of a 600-digit value modulo a 617-digit prime | about 3,500 a second |
biggcd$() of two 600-digit numbers | about 18,000 a second |
biglcm$() of two 600-digit numbers | about 14,000 a second |
bigpow$(2, 10000): a power of 3,011 digits | about 21,000 a second |
bigsqrt$() of a 2,000-digit number | about 21,000 a second |
bigroot$(): the cube root of a 2,000-digit number | about 7,000 a second |
bigand$() of two 1,000-digit numbers | about 11,000 a second |
bigtobase$() of a 1,000-digit number in base 16 | about 33,000 a second |
bigfrombase$() of 831 hex digits, back to 1,000 digits | about 49,000 a second |
bigshl$() or bigshr$() of a 1,000-digit number by 1,000 bits | about 70,000 a second |
bigtestbit() of a 1,000-digit number | about 65,000 a second |
bigjacobi() of two 600-digit numbers | about 15,000 a second |
bigsqrtmod$() modulo a 617-digit prime | from about 20 to about 100 a second, by the prime |
prevprime$() from a 309-digit start | about 100 a second |
bigrand$() of a 617-digit range | about 170,000 a second |
bigformat$() of a 1,000-digit number | about 140,000 a second |
bigpowmod$() with constant_time: true: the same 2048-bit RSA private-key step | about 160 a second |
The limit is one billion digits, and how long a call takes depends on the work. An add, a subtract or a compare grows in step with the digits: two numbers of 100,000,000 digits add together in about a second. A multiply grows a little faster: two numbers of 5,000,000 digits each multiply together in under half a second, and two numbers of 20,000,000 digits each in about 2 seconds. A divide, and a square root, grow about as a multiply does: 2,000,000 digits divided by 1,000,000 digits takes under a fifth of a second, and 100,000,000 digits by 50,000,000 about 15 seconds. A gcd and an inverse grow with the square of the digits: two numbers of 100,000 digits take about a second. (As performed on a modern PC)
When every value and every answer fits in 54 digits, a REAL is exact and much faster. Reach for big integers past that.
Near the limit, a call takes minutes and gigabytes. A number of 1,000,000,000 digits is a gigabyte of text. Two numbers of 500,000,000 digits each multiply in under two minutes and use 9 to 12 GB of memory along the way (Windows sets aside up to 17 GB); a division or a square root at that size takes several minutes. Plan for that much free memory before working that close to the limit.
Summary: A big integer is a whole number held as an ordinary string
of digits, up to 1,000,000,000 of them, and fourteen functions work on it exactly:
BIGADD$(), BIGSUB$(), BIGMUL$(),
BIGPOW$(), BIGDIV$(), BIGMOD$(),
BIGSQRT$(), BIGROOT$(), BIGFAC$(), BIGCMP(),
BIGPOWMOD$(), BIGINVMOD$(), BIGGCD$()
and BIGLCM$(), with BIGJACOBI(), BIGSQRTMOD$()
and the random BIGRAND$(). Eleven more work on its bits and write it in
other bases, BIGTOBASE$() and BIGFROMBASE$() among
them, and BIGFORMAT$() groups its digits for reading.
ISPRIME(), NEXTPRIME$() and PREVPRIME$() test and find primes
of up to 2,500 digits. Together they carry number theory and the
arithmetic of public-key cryptography, while a REAL stays the right
choice for business numbers.
val() turns one of up to 64 digits back into a REAL.BIGCMP(), not with < or > on the strings.BIGDIV$(), BIGSQRT$() and BIGROOT$() put the remainder in _string$: read it straight away.BIGPOW$() makes a power in one call; BIGPOWMOD$() works a power modulo a number without ever making it.BIGFAC$(n) is n!, and BIGFAC$(n, k) the ways to choose k things from n: bigfac$(49, 6) is 13983816, the odds of a six-number lottery.BIGPOWMOD$() and BIGINVMOD$() are the arithmetic of RSA and Diffie–Hellman.constant_time: true to BIGPOWMOD$() (an odd modulus): its time no longer follows the exponent's bits.bigshr$(-5, 1) is −3.BIGTOBASE$() and BIGFROMBASE$() write and read hex, binary, any base to 36, and raw bytes (base 256).BIGFORMAT$() writes a number with a comma between each three digits, or any separator and group; the comma, underscore and space forms read straight back in.BIGGCD$() of them is '1': the check an RSA key and an inverse need.ISPRIME(), NEXTPRIME$() and PREVPRIME$() take numbers of up to 2,500 digits.BIGRAND$() draws from the system's random source: the starting point for a key.|
Hide Description
|
|
|
Enter or modify the code below, and then click on RUN |
|
Looking for the full power of Sheerpower?
Check out the Sheerpower website. Free to download. Free to use. |