Vieta's formula, I don't get the code

268 Views Asked by At

I know what Vieta's Formula is, and how it works but the code below I don't get it (the marked portion).

int coeff[n] = {0};
coeff[n] = 1; 
int roots[] = { -1, 2, -3, 7 };

for (int i = 1; i <= n; i++) {              \\*
    for (int j = n - i - 1; j < n; j++) {   \\*
        coeff[j] = coeff[j] + (-1) *        \\*
            roots[i - 1] * coeff[j + 1];    \\*
    }                                       \\*
}                                           \\*

cout << "Polynomial Coefficients: "; 
for (int i = n; i >= 0; i--) { 
    cout << coeff[i] << " "; 
} 

Output: Polynomial Coefficients: 1 -5 -19 29 42

1

There are 1 best solutions below

0
On

coeff[j] = coeff[j] + (-1) * roots[i - 1] * coeff[j + 1];

This just build the polynomial, 1 term at a time:

Start with $y=1 → [0, 0, 0, 0, 1]$

Mutltiply by $(x+1) → [0, 0, 0, 1, 1]$
Mutltiply by $(x-2) → [0, 0, 1, -1, 1]$
Mutltiply by $(x+3) → [0, 1, 2, -5, 6]$
Mutltiply by $(x-7) → [1, -5, -19, 29, 42]$