diff --git a/solvers/UMirageMaintenance.pas b/solvers/UMirageMaintenance.pas index 535bbb2..93d184a 100644 --- a/solvers/UMirageMaintenance.pas +++ b/solvers/UMirageMaintenance.pas @@ -31,7 +31,7 @@ type TMirageMaintenance = class(TSolver) private FN: Integer; - FLagrangePolynomialsInN: specialize TList; + FLagrangePolynomialsInN, FLagrangePolynomialsInMinusOne: specialize TList; procedure CalcLagrangePolynomials; public constructor Create; @@ -48,19 +48,23 @@ implementation procedure TMirageMaintenance.CalcLagrangePolynomials; var - sign, i, j: Integer; + sign1, sign2, i, j: Integer; begin FLagrangePolynomialsInN.Clear; + FLagrangePolynomialsInMinusOne.Clear; if FN mod 2 = 0 then - sign := -1 + sign1 := -1 else - sign := 1; + sign1 := 1; + sign2 := 1; // Calculates the polynomials in N and -1. for i := 0 to FN - 1 do begin - FLagrangePolynomialsInN.Add(sign); - sign := -sign; + FLagrangePolynomialsInN.Add(sign1); + sign1 := -sign1; + FLagrangePolynomialsInMinusOne.Add(sign2); + sign2 := -sign2; if i < FN - FN div 2 then begin @@ -81,18 +85,38 @@ begin for j := 2 to FN - i - 1 do FLagrangePolynomialsInN[i] := FLagrangePolynomialsInN[i] div j; end; - end; + + if i < FN div 2 then + begin + // Multiplies by the non-cancelled numerator terms. + for j := FN - i to FN do + FLagrangePolynomialsInMinusOne[i] := FLagrangePolynomialsInMinusOne[i] * j; + // Divides by the non-cancelled denominator terms. + for j := 2 to i + 1 do + FLagrangePolynomialsInMinusOne[i] := FLagrangePolynomialsInMinusOne[i] div j; + end + else begin + // Multiplies by the non-cancelled numerator terms. + for j := i + 2 to FN do + FLagrangePolynomialsInMinusOne[i] := FLagrangePolynomialsInMinusOne[i] * j; + // Divides by the non-cancelled denominator terms. + for j := 2 to FN - i - 1 do + FLagrangePolynomialsInMinusOne[i] := FLagrangePolynomialsInMinusOne[i] div j; + end; +end; end; constructor TMirageMaintenance.Create; begin FLagrangePolynomialsInN := specialize TList.Create; + FLagrangePolynomialsInMinusOne := specialize TList.Create; FN := 0; end; destructor TMirageMaintenance.Destroy; begin FLagrangePolynomialsInN.Free; + FLagrangePolynomialsInMinusOne.Free; inherited Destroy; end; @@ -114,6 +138,8 @@ begin y := StrToInt(split[i]); p := y * FLagrangePolynomialsInN[i]; Inc(FPart1, p); + p := y * FLagrangePolynomialsInMinusOne[i]; + Inc(FPart2, p); end; end; diff --git a/tests/UMirageMaintenanceTestCases.pas b/tests/UMirageMaintenanceTestCases.pas index b3310cf..8114388 100644 --- a/tests/UMirageMaintenanceTestCases.pas +++ b/tests/UMirageMaintenanceTestCases.pas @@ -62,7 +62,7 @@ end; procedure TMirageMaintenanceFullDataTestCase.TestPart2; begin - AssertEquals(-1, FSolver.GetResultPart2); + AssertEquals(1108, FSolver.GetResultPart2); end; { TMirageMaintenanceExampleTestCase } @@ -79,7 +79,7 @@ end; procedure TMirageMaintenanceExampleTestCase.TestPart2; begin - AssertEquals(-1, FSolver.GetResultPart2); + AssertEquals(2, FSolver.GetResultPart2); end; initialization