gpt4 book ai didi

java - 在 Java 中实现选择符号的好方法是什么?

转载 作者:行者123 更新时间:2023-12-01 14:04:52 25 4
gpt4 key购买 nike

...最好是Java。这是我所拥有的:

//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;
}

我想知道是否有更好的方法来做到这一点?

最佳答案

choose(n,k) = n! / (n-k)! k!

You could do something like this in O(k):

public static double choose(int x, int y) {
if (y < 0 || y > x) return 0;
if (y > x/2) {
// choose(n,k) == choose(n,n-k),
// so this could save a little effort
y = x - y;
}

double denominator = 1.0, numerator = 1.0;
for (int i = 1; i <= y; i++) {
denominator *= i;
numerator *= (x + 1 - i);
}
return numerator / denominator;
}

编辑 xy大,如果你继续划分你的答案,你会更慢地溢出(即,对于较大的 x & y 值是安全的):
    double answer = 1.0;
for (int i = 1; i <= y; i++) {
answer *= (x + 1 - i);
answer /= i; // humor 280z80
}
return answer;

关于java - 在 Java 中实现选择符号的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1678690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com