Program BisectionMethodWithTabulation;

Function f(x: Real): Real;
Begin
    f := x * x - 4;  // Приклад функції x^2 - 4 = 0
End;

Procedure TabulateAndFindInterval(Var a, b: Real);
Var
    x, step: Real;
    found: Boolean;
Begin
    step := 0.1;  // Крок табулювання
    x := -10;     // Початок інтервалу для пошуку
    found := False;

    WriteLn('Табулювання функції:');
    While x <= 10 Do
    Begin
        WriteLn('f(', x:0:2, ') = ', f(x):0:4);
        
        // Якщо знайдено інтервал де f(a) * f(b) < 0
        If (f(x) * f(x + step) < 0) Then
        Begin
            a := x;
            b := x + step;
            found := True;
            Break;
        End;
        x := x + step;
    End;

    If not found Then
        WriteLn('Не знайдено інтервалу, де функція змінює знак.');
End;

Procedure Bisection(a, b, Eps: Real);
Var
    c: Real;
    iterations: Integer;
Begin
    iterations := 0;
    While (b - a) > Eps Do
    Begin
        c := (a + b) / 2;
        If f(a) * f(c) < 0 Then
            b := c
        Else
            a := c;
        iterations := iterations + 1;
    End;
    WriteLn('Корінь рівняння: ', c:0:6);
    WriteLn('Кількість ітерацій: ', iterations);
End;

Var
    a, b, Eps: Real;
Begin
    Eps := 0.001;

    // Автоматичне табулювання та пошук інтервалу
    TabulateAndFindInterval(a, b);

    If (a <> b) And (f(a) * f(b) > 0) Then
        WriteLn('Немає кореня на цьому інтервалі')
    Else If (a <> b) Then
        Bisection(a, b, Eps);
End.