Matt23

PascalExpansion

Nov 9th, 2015
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function _Formula(_exponent, _checkbox) {
  2.     this.exponent = Number(_exponent);
  3.     this.line_break = _checkbox;
  4.  
  5.     this.getPascal = function() {
  6.         var array = [1];
  7.         for (var i = 0; i < this.exponent; i++) {
  8.             array.push(array[i] * (this.exponent - i) / (i + 1));
  9.         }
  10.         this.array = array;
  11.     };
  12.  
  13.     this.breakLine = function() {
  14.         if (this.line_break)
  15.             this.answer += "<br>";
  16.     };
  17.  
  18.     this.getAnswer = function() {
  19.         this.getPascal();
  20.         this.answer = "(a + b)" + this.exponent.toString().sup() + " = ";
  21.  
  22.         this.breakLine();
  23.  
  24.         if (this.exponent === 0)
  25.             this.answer += 1;
  26.  
  27.         if (this.exponent > 0) {
  28.             this.answer += "a";
  29.             if (this.exponent > 1)
  30.                 this.answer += this.exponent.toString().sup();
  31.  
  32.             this.answer += " + ";
  33.             this.breakLine();
  34.  
  35.             for (var i = 1; i < this.exponent; i++) {
  36.                 this.answer += this.array[i] + "a";
  37.                 if (this.exponent - i > 1)
  38.                     this.answer += (this.exponent - 1).toString().sup();
  39.  
  40.                 this.answer += "b";
  41.                 if (i > 1)
  42.                     this.answer += i.toString().sup();
  43.                 this.answer += " + ";
  44.                 this.breakLine();
  45.             }
  46.  
  47.             this.answer += "b";
  48.             if (this.exponent > 1)
  49.                 this.answer += this.exponent.toString().sup();
  50.         }
  51.         return this.answer;
  52.     };
  53. }
  54.  
  55. function isNumber(n) {
  56.     return !isNaN(parseFloat(n)) && isFinite(n) && (n >= 0) && (n % 1 === 0);
  57. }
  58. window.onload = function() {
  59.     var input = document.getElementById('exponent');
  60.     var checkbox = document.getElementById('line_break');
  61.     var result = document.getElementById('result');
  62.  
  63.     input.oninput = checkbox.onclick = function() {
  64.         if (!isNumber(input.value))
  65.             return result.innerHTML = "The exponent must be non-negative integer!";
  66.  
  67.         var formula = new _Formula(input.value, checkbox.checked);
  68.         result.innerHTML = formula.getAnswer();
  69.     };
  70. };
Advertisement
Add Comment
Please, Sign In to add comment