排列实现
public int arrange(int n, int r) {
if (n < r || n < 0 || r < 0) {
return -1;
}
if (n == r) {
return 1;
}
//从n个不同元素中取r个按序排列
long molecular = 1, denominator = n - r;
int count = n;
while (count > 0) {
molecular *= (count--);
while (denominator > 0 && molecular % denominator == 0) {
molecular /= denominator;
denominator--;
}
}
return (int) molecular;
}
组合实现
public static int combine(int n, int r) {
if (n < r || n < 0 || r < 0) {
return -1;
}
if (n == r) {
return 1;
}
r = Math.min(n - r, r);
//分子
long molecular = 1;
//分母 消去部分分母的乘数个数count 从t开始向下count个
int denominator = r, count = r, t = n;
while (count-- > 0) {
molecular *= (t--);
//计算的时候就进行除法,防止溢出
while (denominator > 0 && molecular % denominator == 0) {
molecular /= denominator;
denominator--;
}
}
return (int) molecular;
}
注意事项