50 lines
1.2 KiB
TypeScript
50 lines
1.2 KiB
TypeScript
|
class Horner {
|
||
|
|
||
|
constants: number[];
|
||
|
|
||
|
constructor(constants: number[]) {
|
||
|
this.constants = constants;
|
||
|
}
|
||
|
|
||
|
candidates() {
|
||
|
// Not effective solution
|
||
|
let max = Math.abs(this.constants[0]) + Math.abs(this.constants[this.constants.length - 1]);
|
||
|
let min = 1;
|
||
|
let candidates: number[] = [];
|
||
|
for(let i = min; i<=max; i++) {
|
||
|
candidates.push(i);
|
||
|
candidates.push(-i);
|
||
|
}
|
||
|
return candidates;
|
||
|
}
|
||
|
|
||
|
functional_value(number: number) {
|
||
|
let new_polynom = [this.constants[0]];
|
||
|
for(let i=1; i<this.constants.length; i++) {
|
||
|
new_polynom.push(this.constants[i] + (new_polynom[new_polynom.length - 1] * number));
|
||
|
}
|
||
|
return new_polynom;
|
||
|
}
|
||
|
|
||
|
functional_value_0(): [number[], number] | void {
|
||
|
let c = this.candidates();
|
||
|
for(let i=0; i<c.length; i++) {
|
||
|
let new_polynom = this.functional_value(c[i]);
|
||
|
if(new_polynom[new_polynom.length - 1] == 0) return [new_polynom, c[i]];
|
||
|
}
|
||
|
}
|
||
|
|
||
|
static roots(horner: Horner) {
|
||
|
let roots: number[] = [];
|
||
|
while(true) {
|
||
|
let r = horner.functional_value_0();
|
||
|
if(!r) return [roots, horner.constants];
|
||
|
let [new_polynom, root] = r;
|
||
|
roots.push(root);
|
||
|
new_polynom.pop();
|
||
|
if(new_polynom.length < 3) return [roots, new_polynom];
|
||
|
horner = new Horner(new_polynom);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|