# Big Integer redux

I started a project that will include Big Integer math implementation (common Delphi&FPC codebase) based on interfaces without objects. Right now the project reached the stage where I am able to compile (and run!) code like that:

```{
Usage example: BinomCoff 120 42
Demonstrates how to use BigCardinal type
http://rosettacode.org/wiki/Evaluate_binomial_coefficients#Delphi
}
program BinomCoff;

{\$APPTYPE CONSOLE}

uses
SysUtils, tfNumerics;

function BinomialCoff(N, K: Cardinal): BigCardinal;
var
L: Cardinal;

begin
if N < K then
Result:= 0      // Error
else begin
if K > N - K then
K:= N - K;    // Optimization
Result:= 1;
L:= 0;
while L < K do begin
Result:= Result * (N - L);
Inc(L);
Result:= Result div L;
end;
end;
end;

var
A: BigCardinal;
M, N: Cardinal;

begin
ReportMemoryLeaksOnShutdown:= True;
try
if ParamCount <> 2 then begin
Writeln('Usage example: BinomCoff 120 42');
Exit;
end;
N:= StrToInt(ParamStr(1));
M:= StrToInt(ParamStr(2));
A:= BinomialCoff(N, M);
Writeln('C(', N, ', ', M, ') = ', A.AsString);
A:= BigCardinal(nil);   // A is global var and should be freed explicitely
//   to prevent memory leak on shutdown
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
```

Output:

A lot still yet to be done, but it works! ðŸ™‚

## 9 thoughts on “Big Integer redux”

1. Why not just use objects?

If you want objects with a variable instance size, just manually alloc a block of memory, manually initialize the VMT pointer, and cast the block pointer to the class type. That way you don’t have to redo the COM plumbing, and you can use regular methods for all the internal processing.

• Never tried that; I can’t say are objects with variable instance size better or not, probably no difference at all. I don’t think it make sense to try it now though, when most low-level dirty work is already done.

3. Well, I would not use interfaces or classes here. You are creating an arithmetic type. So you want operator overloading. So that you can write a := b + c and so on. And that calls for a record.

4. @jpluimers, @David Heffernan – BigCardinal is a record with overloaded operators ðŸ™‚

```type
BigCardinal = record
private
FNumber: IBigNumber;
public
class operator Implicit(const Value: BigCardinal): IBigNumber; inline;
{..etc..}
```

Interface is used on a lower implementation level. The only possible alternative to an interface is a dynarray, but interface is a better alternative, most interesting for me is dll implementation of arbitrary precision math based on COM.

• I feel a big sigh of relief here (:

5. I’m liking the idea of using objects myself. Code such as “Integer.ToString” or whatever really fits nicely into the current OO approach.

• That’s why XE3 introduced “record helpers” for simple types….

6. BigInteger exists in Fundamentals lib. U probably know.