#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

// Define the function f(x) = x^3 - x - 3
double f(double x) {
    return pow(x, 3) - x - 3;
}

int main() {
    double x1, x2, x3, f1, f2;
    const double tolerance = 1e-6;
    const int max_iterations = 100;
    int iteration = 1;

    // Prompt user for initial guesses
    cout << "Enter the value of x1: ";
    cin >> x1;
    cout << "Enter the value of x2: ";
    cin >> x2;

    cout << fixed << setprecision(6);
    cout << "\nIteration\tx1\t\tx2\t\tx3\t\tf(x1)\t\tf(x2)\n";

    while (iteration <= max_iterations) {
        f1 = f(x1);
        f2 = f(x2);

        // Prevent division by zero
        if (fabs(f2 - f1) < 1e-12) {
            cout << "Denominator too small. Division by zero risk.\n";
            break;
        }

        // Compute next approximation
        x3 = (f2 * x1 - f1 * x2) / (f2 - f1);

        // Display current iteration
        cout << iteration << "\t\t" << x1 << "\t" << x2 << "\t" << x3 << "\t" << f1 << "\t" << f2 << "\n";

        // Check for convergence
        if (fabs((x3 - x2) / x3) < tolerance) {
            cout << "\nApproximate root = " << x3 << endl;
            break;
        }

        // Prepare for next iteration
        x1 = x2;
        x2 = x3;
        iteration++;
    }

    if (iteration > max_iterations) {
        cout << "Method did not converge within the maximum number of iterations.\n";
    }

    return 0;
}
