在Java中实现选择表示法的好方法是什么?
...最好是用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;
}
我想知道是否有更好的方法来做到这一点?
... 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你可以在 O(k) 中做这样的事情:
EDIT 如果
x
和y
很大,你会溢出得更慢(即,对于较大的 x 和 y 值来说是安全的)如果你一边做一边除以你的答案: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:您正在处理的数字将变得非常大,并且很快就会超过 double 值的精度,从而给您带来意想不到的错误结果。因此,您可能需要考虑任意精度的解决方案,例如使用 java.math.BigInteger,它不会遇到此问题。
The numbers you are dealing with will become quite large and will quickly exceed the precision of
double
values, giving you unexpectedly wrong results. For this reason you may want to consider an arbitrary-precision solution such as usingjava.math.BigInteger
, which will not suffer from this problem.老实说,你所得到的对我来说看起来很清楚。诚然,我会将 return 语句放在大括号中,因为这是我遵循的约定,但除此之外,它看起来已经尽善尽美了。
我想我可能会颠倒第二个循环的顺序,以便两个循环都是升序的。
正如格雷格所说,如果您需要获得大量数据的准确答案,您应该考虑其他数据类型。鉴于结果应始终为整数,您可能需要选择
BigInteger
(尽管进行了所有除法,结果始终是整数):What you've got looks pretty clear to me, to be honest. Admittedly I'd put the return statements in braces as that's the convention I follow, but apart from that it looks about as good as it gets.
I think I'd probably reverse the order of the second loop, so that both loops are ascending.
As Greg says, if you need to get accurate answers for large numbers, you should consider alternative data types. Given that the result should always be an integer, you might want to pick
BigInteger
(despite all the divisions, the result will always be an integer):我用 C# 编写了此代码,但我尝试使其尽可能适用于 Java。
源自其中一些来源,加上我的一些小东西。
代码:
I coded this in C#, but I tried to make it as applicable as possible to Java.
Derived from some of these sources, plus a couple small things from me.
Code:
为了
使用这个(伪代码)
for
use this (Pseudocode)
此版本不需要 BigInteger 或浮点算术,并且对于小于 62 的所有
n
都不会出现溢出错误。超过 28 的 62 是第一对导致溢出的结果。下面的测试证明这是真的:
This version does not require
BigInteger
or floating-point arithmetic and works without overflow errors for alln
less than 62. 62 over 28 is the first pair to result in an overflow.The following test proves that this is true: