Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Formula(exponent, checkbox) {
- this.n = Number(exponent);
- this.line_break = checkbox;
- //breaking line if checkbox is checked, after every plus mark
- this.breakLine = function() {
- if (this.line_break)
- this.answer += "<br>";
- };
- //getting coefficients using Pascal's triangle
- this.getPascal = function() {
- var coefficients = [1];
- for (var i = 0; i < this.n; i++)
- coefficients.push(coefficients[i] * (this.n - i) / (i + 1));
- this.coef = coefficients;
- };
- this.makeFormula = function() {
- this.getPascal();
- this.answer = "(a + b)" + this.n.toString().sup() + " = ";
- this.breakLine();
- for (var k = 0; k <= this.n; k++) {
- if (this.coef[k] > 1) //don't want to show coefficient equal to 1
- this.answer += this.coef[k];
- //if exponent is equal to 0, the "a" is not shown
- if (this.n - k !== 0) {
- this.answer += "a";
- if (this.n - k > 1) //if exponent is equal to 1, exponent is not shown
- this.answer += (this.n - k).toString().sup();
- }
- //if exponent is equal to 0, the "b" is not shown
- if (k !== 0) {
- this.answer += "b";
- if (k > 1) //if exponent is equal to 1, exponent is not shown
- this.answer += k.toString().sup();
- }
- //adding plus mark excluding end of formula
- if (k != this.n) this.answer += " + ";
- this.breakLine();
- }
- //for n equal to 0 above loop doesn't work
- if (this.n === 0)
- this.answer += 1;
- return this.answer;
- };
- }
- function isNumber(n) {
- return !isNaN(parseFloat(n)) && isFinite(n) && (n >= 0) && (n % 1 === 0);
- }
- window.onload = function() {
- var input = document.getElementById('exponent');
- var checkbox = document.getElementById('line_break');
- var result = document.getElementById('result');
- input.oninput = checkbox.onclick = function() {
- if (!isNumber(input.value))
- return result.innerHTML = "The exponent must be non-negative integer!";
- var formula = new Formula(input.value, checkbox.checked);
- result.innerHTML = formula.makeFormula();
- };
- };
Advertisement
Add Comment
Please, Sign In to add comment