Why is my sub-factor feature disabled?

I'm working on implementing a sub-factorial function in JavaScript to calculate the total number of possible interference for elements n, and I seem to screw something up. My calculation always seems to be one high, or one low. What have I messed up? Is this a rounding error?

function subfactorial (x) {
  x = parseInt(x);
  var i;
  var sub = 0;
  var sum = 0;
  sum += factorial(x);
  for (i = 0; i < x; i++) {
    sub += (Math.pow(-1, i)/factorial(i));
  }
  return sum * sub;
}

function factorial (y) {
  var negative = y < 0;
  y = parseInt(Math.abs(y)); // Ints only
  var acc = 1;
  for (y; y > 0; y--) {
    acc *= y;
  }
  return negative ? -acc : acc;
}

function getSubfactorial () {
  var val = document.getElementById('subfac').value;
  document.getElementById('result').innerHTML = subfactorial(val);
}
<label for="subfac">Subfactorial input:</label>
<input type="number" id="subfac">
<button type="button" onClick="getSubfactorial()">Get Subfactorial</button>
<div id="result"></div>
Run codeHide result

For example, it subfactorial(3)returns 3 when the answer should be 2. subfactorial(4)returns 8 when the answer should be 9. subfactorial(5)returns 45 (with a rounding error with a floating point), when the answer should be 44, etc. Etc. The alternation seems to be too low and too high between even and odd numbers respectively.

The formula I use is as follows:

In TeX:

!x = x! \sum_{k=0}^{x}\frac {(-1)^k}{k!}

Rendered TeX:

4LtRZIE.png

+4
3

:

for (i = 0; i < x; i++) {

, Sum.

for (i = 0; i <= x; i++) {

, . - " ", Javascript 10 . ( ) . 1/k! x!, x!/k!,

var factDiv = function(x, k) {
  return (k >= x) ? 1 : (x * factDiv(x-1,k)); 
}

subfactorial()

var subfactorial = x => {
  var p = 1;
  var sum = 0;
  for (var k=0; k <= x; k++) {
    sum += p * factDiv(x, k);
    p *= -1;
  }
  return sum;
}
+7

= 0 . for

function subfactorial (x) {
  x = parseInt(x);
  var i;
  var sub = 0;
  var sum = 0;
  sum += factorial(x);
  for (i = 0; i <= x; i++) {
    sub += (Math.pow(-1, i)/factorial(i));
  }
  return sum * sub;
}

function factorial (y) {
  var negative = y < 0;
  y = parseInt(Math.abs(y)); // Ints only
  var acc = 1;
  for (y; y > 0; y--) {
    acc *= y;
  }
  return negative ? -acc : acc;
}

function getSubfactorial () {
  var val = document.getElementById('subfac').value;
  document.getElementById('result').innerHTML = subfactorial(val);
}
<label for="subfac">Subfactorial input:</label>
<input type="number" id="subfac">
<button type="button" onClick="getSubfactorial()">Get Subfactorial</button>
<div id="result"></div>
Hide result
+3

, .

for (i = 0; i <= x; i++) {
    sub += (Math.pow(-1, i)/factorial(i));
}

Change the loop to i <= x. However, some rounding problems. This is probably javascript. It looks like he is now getting the correct numbers.

+2
source

All Articles