ZetCode

Big integers in Pascal

last modified November 19, 2026 Free Pascal 3.2.2

The largest signed built-in integer in Free Pascal is Int64, which holds values up to 9,223,372,036,854,775,807. Factorials, powers, and cryptographic numbers pass that limit quickly, and the compiler does not check overflow by default: the value wraps around silently. This article implements an arbitrary-precision integer as an array of base 109 limbs, starting with a two-limb value and a print routine, then adds small-factor multiplication, a unit for the routines, addition, and full multiplication.

Why Int64 is not enough

20! is 2,432,902,008,176,640,000, which fits in an Int64. Multiplying by 21 would need about 2.4 times the maximum value, and a signed 64-bit integer cannot represent it. Without overflow checking the product wraps around to a negative number, which is a plausible-looking but completely wrong result. The -Co switch turns overflow into a runtime error, but no compiler switch can make the type larger.

int64fact.pas
program int64fact;
{$mode objfpc}{$H+}

uses SysUtils;

var
  F: Int64;
  I: Integer;

begin
  F := 1;
  for I := 1 to 20 do
    F := F * I;
  WriteLn('20! = ', F);

  F := F * 21;
  WriteLn('21! = ', F);
  WriteLn('fits: ', F > 0);
end.

The last line is a crude test: a positive Int64 that is supposed to be a factorial cannot be negative, so the sign reveals the wrap. A program cannot rely on that check for addition or for even numbers of wraps. Compiling with -Co makes the multiplication raise EIntOverflow with message Arithmetic overflow instead of producing the negative value, which is the right behaviour for code that must not continue with a wrong number.

$ fpc -gl int64fact.pas
$ ./int64fact
20! = 2432902008176640000
21! = -4249290049419214848
fits: FALSE

Base 10⁹ limbs

A big integer stores its digits in an array of LongWord values, least significant limb first. Each limb holds a value from 0 to 999,999,999, so a limb is nine decimal digits. Base 109 is convenient because two limbs multiplied together plus a carry fit comfortably in a QWord: the largest product is about 1018, below 264 ≈ 1.8·1019. Printing is easy too, because each limb is exactly nine decimal digits except the most significant one.

limbs.pas
program limbs;
{$mode objfpc}{$H+}

uses SysUtils;

const
  Base = 1000000000;

type
  TBig = record
    Digits: array of LongWord;
  end;

procedure PrintBig(const A: TBig);
var
  I: Integer;
begin
  Write(A.Digits[High(A.Digits)]);
  for I := High(A.Digits) - 1 downto 0 do
    Write(Format('%.9d', [A.Digits[I]]));
  WriteLn;
end;

var
  A: TBig;

begin
  SetLength(A.Digits, 2);
  A.Digits[0] := 123456789;
  A.Digits[1] := 1;
  PrintBig(A);
end.

The array holds [123456789, 1], so the value is 1·109 + 123456789 = 1,123,456,789. PrintBig writes the top limb without padding and every lower limb with Format('%.9d', ...), which restores the leading zeros inside a limb. Without that padding, the value would print as 1123456789 either way here, but a lower limb such as 45 would lose eight zeros.

$ fpc -gl limbs.pas
$ ./limbs
1123456789

Multiplying by a small factor

FromInt creates a one-limb value, and MulSmall multiplies every limb by a factor that fits in a LongWord. It adds the carry from the previous limb, stores the low nine digits, and passes the rest on. After the last limb, any remaining carry is appended as new limbs.

bigfact.pas
program bigfact;
{$mode objfpc}{$H+}

uses SysUtils;

const
  Base = 1000000000;

type
  TBig = record
    Digits: array of LongWord;
  end;

procedure FromInt(var A: TBig; N: LongWord);
begin
  SetLength(A.Digits, 1);
  A.Digits[0] := N;
end;

procedure MulSmall(var A: TBig; M: LongWord);
var
  I: Integer;
  Carry: QWord;
  P: QWord;
begin
  Carry := 0;
  for I := 0 to High(A.Digits) do
  begin
    P := QWord(A.Digits[I]) * M + Carry;
    A.Digits[I] := P mod Base;
    Carry := P div Base;
  end;
  while Carry > 0 do
  begin
    SetLength(A.Digits, Length(A.Digits) + 1);
    A.Digits[High(A.Digits)] := Carry mod Base;
    Carry := Carry div Base;
  end;
end;

procedure PrintBig(const A: TBig);
var
  I: Integer;
begin
  Write(A.Digits[High(A.Digits)]);
  for I := High(A.Digits) - 1 downto 0 do
    Write(Format('%.9d', [A.Digits[I]]));
  WriteLn;
end;

var
  F: TBig;
  I: Integer;

begin
  FromInt(F, 1);
  for I := 2 to 100 do
    MulSmall(F, I);
  Write('100! = ');
  PrintBig(F);
  WriteLn('limbs: ', Length(F.Digits));
end.

The loop multiplies the running value by every integer from 2 to 100, so the result is 100!. It needs 18 limbs, as the output shows, and has 158 decimal digits. The cast QWord(A.Digits[I]) before the multiplication is essential: a 32-bit multiply would overflow before the carry is added. The printed value matches the known result.

$ fpc -gl bigfact.pas
$ ./bigfact
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
limbs: 18

A unit for big integers

The remaining examples all need the TBig type and the three routines written so far. They move into a unit called bignum. The constant, the type, and the procedure headers form the interface; the bodies form the implementation.

bignum.pas
unit bignum;
{$mode objfpc}{$H+}

interface

const
  Base = 1000000000;

type
  TBig = record
    Digits: array of LongWord;
  end;

procedure FromInt(var A: TBig; N: LongWord);
procedure MulSmall(var A: TBig; M: LongWord);
procedure PrintBig(const A: TBig);

implementation

uses SysUtils;

procedure FromInt(var A: TBig; N: LongWord);
begin
  SetLength(A.Digits, 1);
  A.Digits[0] := N;
end;

procedure MulSmall(var A: TBig; M: LongWord);
var
  I: Integer;
  Carry: QWord;
  P: QWord;
begin
  Carry := 0;
  for I := 0 to High(A.Digits) do
  begin
    P := QWord(A.Digits[I]) * M + Carry;
    A.Digits[I] := P mod Base;
    Carry := P div Base;
  end;
  while Carry > 0 do
  begin
    SetLength(A.Digits, Length(A.Digits) + 1);
    A.Digits[High(A.Digits)] := Carry mod Base;
    Carry := Carry div Base;
  end;
end;

procedure PrintBig(const A: TBig);
var
  I: Integer;
begin
  Write(A.Digits[High(A.Digits)]);
  for I := High(A.Digits) - 1 downto 0 do
    Write(Format('%.9d', [A.Digits[I]]));
  WriteLn;
end;

end.

The bodies are the same as in the factorial program. SysUtils is listed in the implementation section because only PrintBig needs Format; a program that uses bignum does not get SysUtils through it. The Base constant is in the interface, because the addition and multiplication routines later in the article need it too.

Powers of two

Repeated multiplication by 2 computes a power of two with the same MulSmall routine. 2100 has 31 digits and fits in four limbs; 2200 has 61 digits and needs seven. The program takes FromInt, MulSmall, and PrintBig from the bignum unit, so it consists of the main block only. The example resets the value with FromInt between the two computations, because MulSmall modifies its argument in place.

power.pas
program power;
{$mode objfpc}{$H+}

uses bignum;

var
  P: TBig;
  I: Integer;

begin
  FromInt(P, 1);
  for I := 1 to 100 do
    MulSmall(P, 2);
  Write('2^100 = ');
  PrintBig(P);

  FromInt(P, 1);
  for I := 1 to 200 do
    MulSmall(P, 2);
  Write('2^200 = ');
  PrintBig(P);
end.

The loop runs 100 times and doubles the value each time, starting from 1, so the result is 2100. The second loop starts again from 1 and runs 200 times. Both printed values are exact, which is easy to check against a language with built-in big integers or against a calculator. The number of limbs grows by one roughly every 30 doublings, because 230 is close to 109.

$ fpc -gl power.pas
$ ./power
2^100 = 1267650600228229401496703205376
2^200 = 1606938044258990275541962092341162602522202993782792835301376

Adding big numbers

Addition processes both operands limb by limb, adds the carry, and stores the low nine digits. The result may need one more limb than the longer operand when the final carry is nonzero. The Fibonacci sequence is a natural test: each term is the sum of the previous two, and the numbers grow past Int64 after the 92nd term.

fib.pas
program fib;
{$mode objfpc}{$H+}

uses bignum;

procedure AddBig(const A, B: TBig; var R: TBig);
var
  I, N: Integer;
  Carry, Sum: QWord;
begin
  if Length(A.Digits) > Length(B.Digits) then
    N := Length(A.Digits)
  else
    N := Length(B.Digits);
  SetLength(R.Digits, N);
  Carry := 0;
  for I := 0 to N - 1 do
  begin
    Sum := Carry;
    if I <= High(A.Digits) then
      Sum := Sum + A.Digits[I];
    if I <= High(B.Digits) then
      Sum := Sum + B.Digits[I];
    R.Digits[I] := Sum mod Base;
    Carry := Sum div Base;
  end;
  if Carry > 0 then
  begin
    SetLength(R.Digits, N + 1);
    R.Digits[N] := Carry;
  end;
end;

var
  A, B, C: TBig;
  I: Integer;

begin
  FromInt(A, 1);
  FromInt(B, 1);
  for I := 3 to 200 do
  begin
    AddBig(A, B, C);
    A := B;
    B := C;
  end;
  Write('F(200) = ');
  PrintBig(B);
  WriteLn('limbs: ', Length(B.Digits));
end.

The variables hold consecutive Fibonacci numbers: A is F(i-2), B is F(i-1), and C becomes F(i). The assignments rotate the three records; because the digits are a dynamic array, the assignment is a reference copy, but the next AddBig writes into C with SetLength, which detaches it, so the rotation is safe. F(200) has 42 decimal digits and five limbs.

$ fpc -gl fib.pas
$ ./fib
F(200) = 280571172992510140037611932413038677189525
limbs: 5

Multiplying two big numbers

Schoolbook multiplication computes every pair of limbs, adds the product to the result position, and propagates the carry. For operands with m and n limbs the work is m·n multiplications, which is fine for the sizes here but becomes slow for thousands of digits. The example squares 264, a value that no longer fits in a QWord, and checks the product against 2128 computed by repeated doubling.

mulbig.pas
program mulbig;
{$mode objfpc}{$H+}

uses bignum;

procedure MulBig(const A, B: TBig; var R: TBig);
var
  I, J: Integer;
  Carry, Cur: QWord;
begin
  SetLength(R.Digits, Length(A.Digits) + Length(B.Digits));
  for I := 0 to High(R.Digits) do
    R.Digits[I] := 0;

  for I := 0 to High(A.Digits) do
  begin
    Carry := 0;
    for J := 0 to High(B.Digits) do
    begin
      Cur := QWord(R.Digits[I + J]) +
             QWord(A.Digits[I]) * B.Digits[J] + Carry;
      R.Digits[I + J] := Cur mod Base;
      Carry := Cur div Base;
    end;
    R.Digits[I + Length(B.Digits)] := Carry;
  end;

  while (Length(R.Digits) > 1) and (R.Digits[High(R.Digits)] = 0) do
    SetLength(R.Digits, Length(R.Digits) - 1);
end;

var
  A, R, Check: TBig;
  I: Integer;

begin
  FromInt(A, 1);
  for I := 1 to 64 do
    MulSmall(A, 2);
  Write('2^64        = ');
  PrintBig(A);

  MulBig(A, A, R);
  Write('2^64 * 2^64 = ');
  PrintBig(R);

  FromInt(Check, 1);
  for I := 1 to 128 do
    MulSmall(Check, 2);
  Write('2^128       = ');
  PrintBig(Check);
end.

MulBig allocates a result with room for both operands' limbs, zeroes it, and adds one row of partial products per limb of A. Position I + J receives the product of limbs I and J, and the carry moves on to the next position. The final loop removes leading zero limbs, which appear when the top row contributes nothing. The square of 264 matches 2128 built by MulSmall, so the two routines confirm each other.

$ fpc -gl mulbig.pas
$ ./mulbig
2^64        = 18446744073709551616
2^64 * 2^64 = 340282366920938463463374607431768211456
2^128       = 340282366920938463463374607431768211456

Next steps

The arrays and dynamic arrays articles explain the storage that the limbs use, and the bit manipulation article shows the fixed-width integers that the base 109 limbs are built from. The complex numbers article applies the same custom-type technique to a different numeric type, and the scientific simulations article shows where the precision of ordinary reals runs out.

Source

Free Pascal Reference guide: integer types

Arbitrary-precision arithmetic on Wikipedia

Factorial on Wikipedia

In this article we saw Int64 overflow, stored big integers as base 109 limbs, printed a two-limb value, multiplied by a small factor, moved the routines into a unit, added two values, implemented schoolbook multiplication, and computed 100!, 2200, F(200), and 2128. The series continues with complex numbers in Pascal.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.