C(n,r) 计算器程序不工作

C(n,r) calculator program doesn't work

我使用 java Netbeans JFrameform 制作了一个 C(n,r) 计算器。

here is the frame

这是代码:-

private void lllActionPerformed(java.awt.event.ActionEvent evt) {
    int n=Integer.parseInt(t1.getText());
    int r=Integer.parseInt(t2.getText());
    int s=1;
    for(int i=1;i<=n;i=i+1){
        s=i*s;
    }
    int p=1;
    for(int j=1;j<=n-r;j=j+1){
        p=j*p;
    }
    int q=1;
    for(int k=1;k<=r;k=k+1){
        q=k*q;
    }
    int re=s/(p*q);
    t3.setText(" "+re);
}

代码适用于 n 到 12 的值。但是对于 13 及以后,代码开始给出错误的答案。

wrong output

为什么会这样?感谢您的帮助。

试试这个

private void lllActionPerformed(java.awt.event.ActionEvent evt) {
    int n=Integer.parseInt(t1.getText());
    int r=Integer.parseInt(t2.getText());
    if (r > n / 2) r = n - r; // because C(n, r) == C(n, n - r)
    long ans = 1;
    int i;
    for (i = 1; i <= r; i++) {
        ans *= n - r + i;
        ans /= i;
    }

    t3.setText(" "+ans);
}

在计算过程中,该值超过 Integer.MAX_VALUE This is an overflow of arithmetic operation:

Integer overflow can be demonstrated through an odometer overflowing, a mechanical version of the phenomenon. All digits are set to the maximum 9 and the next increment of the white digit causes a cascade of carry-over additions setting all digits to 0, but there is no higher digit to change to a 1, so the counter resets to zero. This is wrapping in contrast to saturating. In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.

尝试用 long 值替换 int。它将具有更大的价值。

private void lllActionPerformed(java.awt.event.ActionEvent evt) {
    int n=Integer.parseInt(t1.getText());
    int r=Integer.parseInt(t2.getText());
    int s=1;
    for(int i=1;i<=n;i=i+1){
        s=i*s;
    }
    long p=1L;
    for(int j=1;j<=n-r;j=j+1){
        p=j*p;
    }
    long q=1L;
    for(int k=1;k<=r;k=k+1){
        q=k*q;
    }
    long re=s/(p*q);
    t3.setText(" "+re);
}

输入 14 和 2 结果为 91。

如果你想获得大值的正确结果,你必须使用 BigInteger 来处理:

Immutable arbitrary-precision integers