clear; clc;

a = 1; % lower bound
b = 2; % upper bound
eps = 1e-9; % error tolerance

cnt = 0;
while b - a > eps
    
    cnt = cnt + 1;
    c = (a + b) / 2;

    fa = a ^ 3 - a - 2;
    fb = b ^ 3 - b - 2;
    fc = c ^ 3 - c - 2;

    if fa * fc < 0 % equivalent to if (fa > 0 && fc < 0) || (fa < 0 && fc > 0)
        b = c; % update the upper bound
    else
        a = c; % update the lower bound
    end
end
root = c
residue = fc
cnt

%%%% For all polynomials, you can find all roots by using vectors and the
%%%% function roots, say

p = [1, 0, -1, -2]
r = roots(p)
residue2 = r(1) ^ 3 - r(1) - 2