Saturday, May 10, 2008

Yet another combinations algorithm

I have found this cool algorithm for calculating combinations(nCr). The conventional algorithm is like this
n!
---------
r!(n-r)!

and this is O(n3). as calculating each of the factorials is at least O(n)
The following is my new algorithm that saves memory and also running time written in C++:

long int choose(int n,int r){
//double ensures that precession is preserved
//when dividing as int rounds up the dividend in C++

double num,den,comb=1;

if (n == 0 || n == r){
return 1;
}else{
for (i=0; i<r || i<(n-r) ; i++){
num = double(n-i);
den = double(i+1);
comb *= num/den;
}
}
return comb;
}


This is O(n) because of the for loop.