... preferably in Java. Here is what I have:
//x choose y
public static double choose(int x, int y) {
if (y < 0 || y > x) return 0;
if (y == 0 || y == x) return 1;
double answer = 1;
for (int i = x-y+1; i <= x; i++) {
answer = answer * i;
}
for (int j = y; j > 1; j--) {
answer = answer / j;
}
return answer;
}
I'm wondering if there's a better way of doing this?
You could do something like this in O(k):
EDIT If
x
andy
are large, you will overflow more slowly (i.e., be safe for larger values of x & y) if you divide your answer as you go along: