program NextCubeSeries;
{$mode objfpc}{$H+}{$J-} // Use modern Object Pascal dialect, Ansistrings, and read-only constants
{
This program finds the next number in a sequence of perfect cubes.
The input series is: 1, 8, 27, 64, 125, 216
These values correspond to:
1^3, 2^3, 3^3, 4^3, 5^3, 6^3
The next value is 7^3 = 343.
The approach:
- Verify each number is a perfect cube.
- Extract the cube root of the last number.
- Compute (root + 1)^3 to get the next number.
}
uses
Math; { for Power() and Round() }
{
Free Pascal does not provide cbrt(), so we implement a small helper.
CubeRoot(x) = x^(1/3)
}
function CubeRoot(Value: Double): Double;
begin
Result := Power(Value, 1.0 / 3.0);
end;
{ Check whether a number is a perfect cube }
function IsPerfectCube(Value: Integer): Boolean;
var
Root: Double;
Rounded: Integer;
begin
Root := CubeRoot(Value); { cube root }
Rounded := Round(Root); { nearest integer }
Result := (Rounded * Rounded * Rounded) = Value;
end;
{ Compute the next cube in the series }
function NextCubeInSeries(const Series: array of Integer): Integer;
var
LastValue: Integer;
LastRoot: Integer;
begin
LastValue := Series[High(Series)]; { last element }
LastRoot := Round(CubeRoot(LastValue));
Result := (LastRoot + 1) * (LastRoot + 1) * (LastRoot + 1);
end;
var
Series: array[0..5] of Integer = (1, 8, 27, 64, 125, 216);
I: Integer;
NextValue: Integer;
begin
{ Validate the pattern before computing the next value }
for I := Low(Series) to High(Series) do
begin
if not IsPerfectCube(Series[I]) then
begin
WriteLn('Series contains a non-cube value.');
Halt(1);
end;
end;
NextValue := NextCubeInSeries(Series);
WriteLn('Next number in the series: ', NextValue);
end.
{
run:
Next number in the series: 343
}