-
-
Save martinkadlec0/1926015 to your computer and use it in GitHub Desktop.
Polynom operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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