A uLisp extension for arbitrary-precision arithmetic


This is a small arbitrary-precision extension for uLisp, for calculating with large integers. It is designed to work on any 32-bit uLisp platform. To add these functions:

  • Uncomment #define extensions at the start of the main uLisp source file.
  • Compile and upload uLisp with the file Bignums.ino included in the same folder as the uLisp source file for your platform.

The bignum functions will then be added to the built-in functions in uLisp.

Here is the Bignums Extension: Bignums.ino.

Or get it from GitHub at: https://github.com/technoblogy/ulisp-bignums.


I’ve been trying to think of a good example to test the new Extensions File feature introduced in uLisp Release 4.4, and thought it would be interesting to add an arbitrary precision package.

It’s similar in function to the uLisp example program Infinite precision arithmetic, but with the following differences:

  • It’s written in C, so faster.
  • Numbers are packed as efficiently as possible, 32 bits per Lisp object.
  • It supports a wider range of functions, including division, modulus, comparisons, and bitwise logical functions.

It was inspired by Kokke’s tiny-bignum-c library on GitHub; his clearly-written routines made me hopeful that this was a project I could complete in a weekend. My library follows the logic of his routines, but rewritten to use uLisp lists rather than C arrays for storing the bignums.

My aim was to make the functions simple to understand, rather than optimising the routines. In particular, I know there are clever ways to improve the bignum multiplication and division; this is left as an exercise for the reader. One of the slowest operations is using $bignum-string to convert a bignum to decimal, because it needs to perform repeated divisions.

Even if you’re not interested in arbitrary-precision arithmetic, but would like to make your own extensions to uLisp, this example should be useful in showing:

  • How to interface C routines with uLisp.
  • How to build a list within a C function.
  • How to construct a uLisp string from within a C function.
  • How to call the garbage collector from C.

I’ve included detailed comments to explain non-obvious features.


This set of uLisp functions use uLisp lists to represent bignums, and takes advantage of the list handling and garbage collection to allow you to work with arbitrarily large numbers, limited only by the amount of Lisp workspace.

The bignum versions of the uLisp functions have the same names as their integer equivalents, but with a ‘$’ prefix. The library provides the following functions:

Function Description
($bignum int) Converts an integer to a bignum.
($integer bignum) Converts a bignum to an integer.
($bignum-string bignum [base]) Converts a bignum to a string; the base is 10 (default) or 16.
($string-bignum bignum [base]) Converts a string to a bignum; the case is 10 (default) or 16.
($zerop bignum) Tests whether a bignum is zero, allowing for trailing zeros.
($+ bignum1 bignum2) Adds two bignums and returns the sum as a new bignum.
($- bignum1 bignum2) Subtracts two bignums and returns the difference as a new bignum.
($* bignum1 bignum2) Multiplies two bignums and returns the product as a new bignum.
($/ bignum1 bignum2) Divides two bignums and returns the quotient as a new bignum.
($mod bignum1 bignum2) Divides two bignums and returns the remainder as a new bignum.
($= bignum1 bignum2) Returns t if the two bignums are equal.
($< bignum1 bignum2) Returns t if bignum1 is less than bignum2.
($> bignum1 bignum2) Returns t if bignum1 is greater than bignum2.
($logand bignum1 bignum2) Returns the logical AND of two bignums.
($logior bignum1 bignum1) Returns the logical inclusive OR of two bignums.
($logxor bignum1 bignum2) Returns the logical exclusive OR of two bignums.
($ash bignum shift) Returns bignum shifted by shift bits; positive means left.



The bignums are represented using standard lists of 32-bit integers. They are packed as efficiently as possible, 32 bits per Lisp object, with the least significant word of a bignum stored in the head or car of the list, and the most significant word in the tail. For example, the following list represents 3 + 17 x 2^32, or 73014444035:

'(3 17)

Garbage collection

Some of the C functions in this arbitrary-precision arithmetic package build temporary lists to hold bignums used during the calculations. Because garbage collection doesn’t occur automatically in C functions, as it does when executing Lisp code, it’s possible for a “no room” error to occur even when there’s plenty of workspace. The solution is to manually call the garbage collector within the C functions. To reduce the time overhead of garbage collections the package includes a function maybe_gc() which only performs a garbage collection if less than 1/16th of the workspace remains.


In the following examples I’ve followed the convention that variables representing bignums are prefixed with ‘$’, although this isn’t required. The timings were all obtained on an ATSAMD51 board (Adafruit ItsyBitsy M4 Express).


The following routine $fact returns the factorial of an integer as a bignum:

(defun $fact (n)
  (let (($result ($bignum 1)))
  (dotimes (i n $result)
    (setq $result ($* $result ($bignum (1+ i)))))))

For example, to find factorial 100 and return it as string representing a decimal number:

> (time ($bignum-string ($fact 100)))
Time: 233 ms


The following routine $expt finds x^y for integer x and y:

(defun $expt (x y)
  (let (($e ($bignum 1))
        ($f ($bignum x)))
     (when (zerop y) (return $e))
     (when (oddp y) (setq $e ($* $e $f)))
     (setq $f ($* $f $f) y (ash y -1)))))

For example, to find 7^160:

> (time ($bignum-string ($expt 7 160)))
Time: 153 ms

Square root

The following routine $sqrt calculates the square root of a bignum using the Newton–Raphson method:

(defun $sqrt ($a)
  (let* (($1 ($bignum 1))
         ($high $a)
         ($low ($bignum 0))
         ($mid ($+ ($ash $high -1) $1)))
     (unless ($> $high $low) (return))
     (if ($> ($* $mid $mid) $a)
         (setq $high ($- $mid $1))
       (setq $low $mid))
     (setq $mid ($+ ($+ $low ($ash ($- $high $low) -1)) $1)))

For example:

> (time ($bignum-string ($sqrt ($string-bignum "152415787532388367501905199875019052100"))))
Time: 32 ms

Further suggestions

The library could be modified to run on 8/16-bit versions of uLisp by making the fundamental building block of bignums uint16_t rather than uint32_t.

I was planning to use the package to write a Lisp example to calculate pi to a large number of digits, but ran out of time. Perhaps someone would like to contribute this. For a good summary of the available algorithms see Meet π on Guy Fernando’s i4cy.com site.

uLisp on the Raspberry Pico W: higher precision?

I think it’s a good addition. Support for big numbers is one of the appealing features of Lisp.



amazing job with uLisp! thanks for making this amazing project.

i tried compiling this in Teensyduino for Teensy 4.1 and got the below errors.

any help appreciated thanks :)

Bignums:563: error: redefinition of ‘tbl_entry_t* tables []’
563 | tbl_entry_t tables[] = {lookup_table, lookup_table2};
| ^~~~~~
/Users/dave/Documents/LISP/uLisp/installs/ARM-4-4c/ulisp-arm/ulisp-arm.ino:6529:14: note: 'tbl_entry_t
tables [2]’ previously defined here
6529 | tbl_entry_t tables[] = {lookup_table, NULL};
| ^~~~~~
Bignums:564: error: redefinition of ‘const unsigned int tablesizes []’
564 | const unsigned int tablesizes[] = { arraysize(lookup_table), arraysize(lookup_table2) };
| ^~~~~~~~~~
/Users/dave/Documents/LISP/uLisp/installs/ARM-4-4c/ulisp-arm/ulisp-arm.ino:6530:20: note: ‘const unsigned int tablesizes [2]’ previously defined here
6530 | const unsigned int tablesizes[] = { arraysize(lookup_table), 0 };
| ^~~~~~~~~~
Bignums:566: error: redefinition of 'tbl_entry_t
566 | const tbl_entry_t *table (int n) {
| ^~~~~
/Users/dave/Documents/LISP/uLisp/installs/ARM-4-4c/ulisp-arm/ulisp-arm.ino:6532:20: note: ‘tbl_entry_t* table(int)’ previously defined here
6532 | const tbl_entry_t *table (int n) {
| ^~~~~
Bignums:570: error: redefinition of ‘unsigned int tablesize(int)’
570 | unsigned int tablesize (int n) {
| ^~~~~~~~~
/Users/dave/Documents/LISP/uLisp/installs/ARM-4-4c/ulisp-arm/ulisp-arm.ino:6536:14: note: ‘unsigned int tablesize(int)’ previously defined here
6536 | unsigned int tablesize (int n) {
| ^~~~~~~~~
Bignums:566: warning: ‘tbl_entry_t* table(int)’ defined but not used
566 | const tbl_entry_t *table (int n) {
| ^~~~~
redefinition of ‘tbl_entry_t* tables []’


Did you uncomment the directive at the start of the uLisp source?

// #define extensions

If you get it working on Teensy 4.1 I’d be interested in how quickly it runs the examples.


thanks, that fixed it. here are some quick tests:

factorial =>

59911> (time ($bignum-string ($fact 100)))
Time: 16 ms

59911> (time ($bignum-string ($fact 500)))
Time: 5.4 s

59911> (time ($bignum-string ($fact 1000)))
Time: 67.0 s

expt =>

59846> (time ($bignum-string ($expt 7 160)))
Time: 12 ms

59846> (time ($bignum-string ($expt 9 999)))
Time: 3.2 s

square root =>

59752> (time ($bignum-string ($sqrt ($string-bignum “152415787532388367501905199875019052100”))))
Time: 2 ms


That’s pretty fast! Thanks.


There’s a more detailed description of the arbitrary-precision arithmetic routines here:

Arbitrary-precision arithmetic extension

I’d welcome any suggestions for improvements!


Here’s a function that uses the arbitrary-precision arithmetic extension to factorise large numbers, using Pollard’s rho algorithm:

(defun $gcd (a b)
  (let (temp)
     (when ($zerop b) (return a))
     (setq temp b b ($mod a b) a temp))))

(defun $pollard-rho (n)
  (let* (($1 ($bignum 1))
         (x ($bignum 2))
         (y ($bignum 2))
         (d ($bignum 1))
         ($g (lambda (x) ($mod ($+ ($* x x) $1) n))))
     (unless ($= d $1) (return))
     (setq x ($g x))
     (setq y ($g ($g y)))
     (setq d ($gcd (if ($> x y) ($- x y) ($- y x)) n)))
    (if ($= d n) nil d)))

For example, it takes 10 minutes on an ATSAMD51 board to find the smallest factor of the ninth Fermat number, which has 155 digits and is:


Here’s the definition of fermat (it needs expt defined earlier):

(defun $fermat (n) ($+ ($expt 2 (expt 2 n)) ($bignum 1)))

and here’s the factor:

> (time ($bignum-string ($pollard-rho ($fermat 9))))
Time: 607.9 s


this thread really takes me back to my undergrad days 89-93 learning functional languages, we did some Lisp, but mainly it was ML. one of our assignments was implementing something like this for arbitrary arithmetic, although i cant remember how we did it…

these tests & previous ones for teensy 4.1 are at 600mhz. have done these ones with 3 optimizations. i did have a go overclocking, but i’m not convinced the teensy is stable for overclocking yet, so i’ll keep at 600mhz for now, as i only have the one unit.

note how on teensy “fastest” is not as fast as “faster”… which seems like strange terminology :) also done ItsyBItsy M4 120mhz with 3 optimizations. note these optimizations are in the order listed in Arduino/Teensyduino IDE to make it easier for anyone looking at the menu.

Teensy 4.1 =>

Mersenne primes
(time (mersenne))
snipped long output

Time: 1.4 s
Time: 3.0 s
Time: 1.5 s

58413> (time ($bignum-string ($pollard-rho ($fermat 9))))

Time: 46.4 s
Time: 92.5 s
Time: 47.5 s

ItsyBitsy M4 =>

Mersenne primes

“fast” (-02)
Time: 13.5 s
“faster” (-03)
Time: 10.1 s
“fastest” (-0fast)
Time: 9.7 s


“fast” (-02)
Time: 421.8 s
“faster” (-03)
Time: 329.7 s
“fastest” (-0fast)
Time: 321.3 s

i probably should have done those as a table… the ItsyBitsy is a SAMD51 and my times are quite different though. what did you run your tests / examples on?

the only difference i can think though is i’ve manually typed in the " and \ chars to get it into my LispLibrary.h, which is pasted below to save folks the typing.

i’m working on some lisp code at the moment and converting it over to uLisp to put in the LispLibrary.h is getting a bit time consuming manually typing the conversion. what would be great for us is a pre-processor or a little script example that could take already written lisp code and add the " chars and put in any needed escape chars … anyway, one to think about, unfortunately not something i have time to investigate at the moment :)

for the LispLibrary.h with " and \ chars added =>

“(defun $fact (n)”
" (let (($result ($bignum 1)))"
" (dotimes (i n $result)"
" (setq $result ($* $result ($bignum (1+ i)))))))"

“(defun $expt (x y)”
" (let (($e ($bignum 1))"
" ($f ($bignum x)))"
" (loop"
" (when (zerop y) (return $e))"
" (when (oddp y) (setq $e ($* $e $f)))"
" (setq $f ($* $f $f) y (ash y -1)))))"

“(defun $sqrt ($a)”
" (let* (($1 ($bignum 1))"
" ($high $a)"
" ($low ($bignum 0))"
" ($mid ($+ ($ash $high -1) $1)))"
" (loop"
" (unless ($> $high $low) (return))"
" (if ($> ($* $mid $mid) $a)"
" (setq $high ($- $mid $1))"
" (setq $low $mid))"
" (setq $mid ($+ ($+ $low ($ash ($- $high $low) -1)) $1)))"
" $low))"

“(defun mersenne ()”
" (dolist (m '(2 3 5 7 13 17 19 31 61 89 107 127 521 607 1279 2203))"
" (let (($p ($- ($expt 2 m) ($bignum 1))))"
" (format t “~4a ~a~%” m ($bignum-string $p)))))"

“(defun $gcd (a b)”
" (let (temp)"
" (loop"
" (when ($zerop b) (return a))"
" (setq temp b b ($mod a b) a temp))))"

“(defun $pollard-rho (n)”
" (let* (($1 ($bignum 1))"
" (x ($bignum 2))"
" (y ($bignum 2))"
" (d ($bignum 1))"
" ($g (lambda (x) ($mod ($+ ($* x x) $1) n))))"
" (loop"
" (unless ($= d $1) (return))"
" (setq x ($g x))"
" (setq y ($g ($g y)))"
" (setq d ($gcd (if ($> x y) ($- x y) ($- y x)) n)))"
" (if ($= d n) nil d)))"

“(defun $fermat (n) ($+ ($expt 2 (expt 2 n)) ($bignum 1)))”


another quick test. pretty respectable on the Raspberry Pi Pico [M0+ 133mhz]

Mersenne primes
Time: 20.1 s
Time: 12.7 s
Time: 12.5 s
Time: 12.0 s

Time: 637.1 s
Time: 416.0 s
Time: 427.3 s
Time: 410.7 s


i got these interesting results from Adafruit Neo Trinkey [M0+ 48mhz]

Mersenne primes

2 3

3 7

5 31

7 127

13 8191

17 131071

19 524287

31 2147483647

61 2305843009213693951

89 618970019642690137449562111

107 162259276829213363391578010288127

127 170141183460469231731687303715884105727

521 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151

607 531137992816767098689588206552468627329593117727031923199444138200403559860852242739162502265229285668889329486246501015346579337652707239409519978766587351943831270835393219031728127

Error: ‘$*’ no room

this was quite a challenge for it, just over an hour, i was just about to kill it :)
Time: 3786.9 s


the ItsyBitsy is a SAMD51 and my times are quite different though. what did you run your tests / examples on?

I used the Adafruit SAMD Boards core version 1.7.2, and I see that the core is now at version 1.7.11. Also, I left the Optimize setting at Small (-Os) (standard).

I’ll try the other settings, and the latest version of the core, and report back.


Arduino Mega doing the Lisp defined examps on this page

(time (fac 26))

Time: 1.3 s

anything larger gives a stack overflow.

(time (iex 2 64))

Time: 2.0 s

bonus extra to see what was the highest from 9 before a stack overflow
(time (iex 9 31))

Time: 2.1 s

highest iex possible before stack overflow in the Mersenne listing:

(time (iex 2 127))

Time: 3.8 s


the ItsyBitsy is a SAMD51 and my times are quite different though. what did you run your tests / examples on?

@clob Yes, I get closer to your timings if I use the Optimize settings.