Matt23

PascalExpansion v2

Nov 10th, 2015
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Formula(exponent, checkbox) {
  2.   this.n = Number(exponent);
  3.   this.line_break = checkbox;
  4.  
  5.   //breaking line if checkbox is checked, after every plus mark
  6.   this.breakLine = function() {
  7.     if (this.line_break)
  8.       this.answer += "<br>";
  9.   };
  10.  
  11.   //getting coefficients using Pascal's triangle
  12.   this.getPascal = function() {
  13.     var coefficients = [1];
  14.     for (var i = 0; i < this.n; i++)
  15.       coefficients.push(coefficients[i] * (this.n - i) / (i + 1));
  16.  
  17.     this.coef = coefficients;
  18.   };
  19.  
  20.   this.makeFormula = function() {
  21.     this.getPascal();
  22.     this.answer = "(a + b)" + this.n.toString().sup() + " = ";
  23.     this.breakLine();
  24.  
  25.     for (var k = 0; k <= this.n; k++) {
  26.       if (this.coef[k] > 1) //don't want to show coefficient equal to 1
  27.         this.answer += this.coef[k];
  28.  
  29.       //if exponent is equal to 0, the "a" is not shown
  30.       if (this.n - k !== 0) {
  31.         this.answer += "a";
  32.         if (this.n - k > 1) //if exponent is equal to 1, exponent is not shown
  33.           this.answer += (this.n - k).toString().sup();
  34.       }
  35.  
  36.       //if exponent is equal to 0, the "b" is not shown
  37.       if (k !== 0) {
  38.         this.answer += "b";
  39.         if (k > 1) //if exponent is equal to 1, exponent is not shown
  40.           this.answer += k.toString().sup();
  41.       }
  42.  
  43.       //adding plus mark excluding end of formula
  44.       if (k != this.n) this.answer += " + ";
  45.       this.breakLine();
  46.     }
  47.  
  48.     //for n equal to 0 above loop doesn't work
  49.     if (this.n === 0)
  50.       this.answer += 1;
  51.  
  52.     return this.answer;
  53.   };
  54. }
  55.  
  56. function isNumber(n) {
  57.   return !isNaN(parseFloat(n)) && isFinite(n) && (n >= 0) && (n % 1 === 0);
  58. }
  59.  
  60. window.onload = function() {
  61.   var input = document.getElementById('exponent');
  62.   var checkbox = document.getElementById('line_break');
  63.   var result = document.getElementById('result');
  64.  
  65.   input.oninput = checkbox.onclick = function() {
  66.     if (!isNumber(input.value))
  67.       return result.innerHTML = "The exponent must be non-negative integer!";
  68.  
  69.     var formula = new Formula(input.value, checkbox.checked);
  70.     result.innerHTML = formula.makeFormula();
  71.   };
  72. };
Advertisement
Add Comment
Please, Sign In to add comment