Added polynomial degree and coefficients as public properties

This commit is contained in:
Stefan Müller 2024-04-04 20:24:56 +02:00
parent 71c8462358
commit 0bbae0a83e
2 changed files with 56 additions and 5 deletions

View File

@ -32,7 +32,11 @@ type
TBigIntPolynomial = object
private
FCoefficients: array of TBigInt;
function GetDegree: Integer;
function GetCoefficient(const AIndex: Integer): TBigInt;
public
property Degree: Integer read GetDegree;
property Coefficient[const AIndex: Integer]: TBigInt read GetCoefficient;
function CalcValueAt(const AX: Int64): TBigInt;
function IsEqualTo(const AOther: TBigIntPolynomial): Boolean;
class function Create(const ACoefficients: array of TBigInt): TBigIntPolynomial; static;
@ -47,6 +51,16 @@ implementation
{ TBigIntPolynomial }
function TBigIntPolynomial.GetDegree: Integer;
begin
Result := Length(FCoefficients) - 1;
end;
function TBigIntPolynomial.GetCoefficient(const AIndex: Integer): TBigInt;
begin
Result := FCoefficients[AIndex];
end;
function TBigIntPolynomial.CalcValueAt(const AX: Int64): TBigInt;
var
i: Integer;
@ -78,16 +92,19 @@ class function TBigIntPolynomial.Create(const ACoefficients: array of TBigInt):
var
high, i: integer;
begin
high := 1;
for i := Length(ACoefficients) - 1 downto 1 do
high := -1;
for i := Length(ACoefficients) - 1 downto 0 do
if ACoefficients[i] <> 0 then
begin
high := i;
Break;
end;
SetLength(Result.FCoefficients, high + 1);
for i := 0 to high do
Result.FCoefficients[i] := ACoefficients[i];
if high >= 0 then
begin
SetLength(Result.FCoefficients, high + 1);
for i := 0 to high do
Result.FCoefficients[i] := ACoefficients[i];
end;
end;
{ Operators }

View File

@ -29,7 +29,13 @@ type
{ TBigIntPolynomialTestCase }
TBigIntPolynomialTestCase = class(TTestCase)
private
procedure TestCreateWithDegree(const ACoefficients: array of TBigInt; const ADegree: Integer);
published
procedure TestCreate;
procedure TestCreateDegreeOne;
procedure TestCreateDegreeZero;
procedure TestCreateDegreeZeroTrim;
procedure TestEqual;
procedure TestUnequalSameLength;
procedure TestUnequalDifferentLength;
@ -41,6 +47,34 @@ implementation
{ TBigIntPolynomialTestCase }
procedure TBigIntPolynomialTestCase.TestCreateWithDegree(const ACoefficients: array of TBigInt; const ADegree: Integer);
var
a: TBigIntPolynomial;
begin
a := TBigIntPolynomial.Create(ACoefficients);
AssertEquals('Degree of created polynomial incorrect.', ADegree, a.Degree);
end;
procedure TBigIntPolynomialTestCase.TestCreate;
begin
TestCreateWithDegree([992123, 7, 20, 4550022], 3);
end;
procedure TBigIntPolynomialTestCase.TestCreateDegreeOne;
begin
TestCreateWithDegree([4007], 0);
end;
procedure TBigIntPolynomialTestCase.TestCreateDegreeZero;
begin
TestCreateWithDegree([], -1);
end;
procedure TBigIntPolynomialTestCase.TestCreateDegreeZeroTrim;
begin
TestCreateWithDegree([0], -1);
end;
procedure TBigIntPolynomialTestCase.TestEqual;
var
a, b: TBigIntPolynomial;