-2

I need to calculate factorials for a bigger function in my spreadsheet (cdf for hypergeometric probabilities). I've tried lots of the ways that have been described in different posts here but none of them give me the correct result. If I plug in (3) I get (2) which makes no sense to me. Can anyone explain what I'm doing wrong?

Also, from what I've read I will face problems with larger factorials because JavaScript can't store very large numbers? I saw one solution suggesting I use strings to represent large integers but It looks very complicated... Any ideas on an easier way to handle this problem?.

Factorial Function:

function MyFac(x) {    
    var fac=x;
    var i=1;

    while (i<x) {        
        fac=fac*i;
        i++;        
    }        

    return fac;        
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
bulkhed
  • 21
  • 2

1 Answers1

0

Where's a correction of your code:

function MyFac(x) {    
    var fac=x;

    while (x>1) {        
        x--;        
        fac=fac*x;
    }        

    return fac;        
}

console.log(MyFac(5))
console.log(MyFac(4))
console.log(MyFac(3))
console.log(MyFac(2))

You can find much better implementations of factorial here:

Fast factorial function in JavaScript

Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73