Skip to content

Instantly share code, notes, and snippets.

@martinkadlec0
Created February 27, 2012 18:29
Show Gist options
  • Select an option

  • Save martinkadlec0/1926015 to your computer and use it in GitHub Desktop.

Select an option

Save martinkadlec0/1926015 to your computer and use it in GitHub Desktop.
Polynom operations
var a = "5x^5+3x^3-7x^2+4x+30";
var b = "8x^5+4x^4-2x^3-2x^2+4x";
function secti(a, b) {
var koefA = getKoef(a);
var koefB = getKoef(b);
var res = '', tmp;
for (var i=Math.max(koefA.length, koefB.length); i--;) {
if (koefA[i] && koefB[i] && (koefA[i] || 0) + (koefB[i] || 0)) {
tmp = koefA[i] + koefB[i];
res += (tmp >=0 ? '+' + tmp : tmp) + (i > 0 ? 'x' : '');
if (i>1) {
res += '^'+i;
}
} else if (tmp = (koefA[i] || koefB[i]) && (koefA[i] || 0) + (koefB[i] || 0)) {
res += (tmp >=0 ? '+' + tmp : tmp) + (i > 0 ? 'x' : '');
if (i>1) {
res += '^'+i;
}
}
}
return res;
}
function getKoef(a) {
var koef = [];
var tmpKoef = '';
var tmpIndex = '';
var role = 0;
var tmpIndexInt;
for (var i=0, j=a.length;i<j;i++) {
if (a[i] == '-' || a[i] == '+') {
if (tmpKoef) {
tmpIndexInt = parseInt(tmpIndex) || 1;
koef[tmpIndexInt] = (koef[tmpIndexInt] || 0) + parseInt(tmpKoef);
tmpIndex = '';
tmpKoef = '';
}
role = 0;
}
if (parseInt(a[i]) == a[i] || a[i] == '-') {
if (role == 0) {
tmpKoef += a[i];
} else {
tmpIndex += a[i]
}
} else if (a[i] == 'x') {
role = 1;
}
}
if (tmpKoef) {
koef[0] = parseInt(tmpKoef);
}
return koef;
}
alert(secti(a, b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment