Looking at your code, it is not surprising that you will run out of memory quickly. Your divideFactorials method calls the factorial method and uses the numerator-denominator difference as an argument. This difference is likely to be very large according to your code, and you will be stuck in a very long loop in your factorial method.
If this is really just a nCk search (which I assume because your comment is in your code), simply use:
public static long GetnCk(long n, long k) { long bufferNum = 1; long bufferDenom = 1; for(long i = n; i > Math.Abs(nk); i--) { bufferNum *= i; } for(long i = k; i => 1; i--) { bufferDenom *= i; } return (long)(bufferNom/bufferDenom); }
Of course, using this method, you quickly run out of range, because long does not actually support very long numbers, so n and k must be less than 20.
Assuming that you are actually working with very large numbers, you can use doubles instead of longs, as the powers are becoming more significant.
Edit: If you use large numbers, you can also use the Stirling Formula:
As n becomes large ln (n!) β n * ln (n) - n.
Introducing this into code:
public static double GetnCk(long n, long k) { double buffern = n*Math.Log(n) - n; double bufferk = k*Math.Log(k) - k; double bufferkn = Math.Abs(nk)*Math.Log(Math.Abs(nk)) - Math.Abs(nk); return Math.Exp(buffern)/(Math.Exp(bufferk)*Math.Exp(bufferkn)); }
I offer this answer only because, as you said, is language independent, C # code is simply used to demonstrate it. Since this requires using large numbers for n and k, I suggest this as a general way to find the binomial coefficient for large combinations.
In cases where n and k are both less than about 200-300, you should use the answer suggested by Victor Mukherjee, as it is.
Edit2: Edited my first code.