Search code examples
javacoding-style

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


I made a C(n,r) calculator using java Netbeans JFrameform.

here is the frame

Here is the code :-

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

the code works well for values values of n upto 12. But for 13 and onward , code starts giving wrong answer.

wrong output

why is this happening? Your help is appreciated.


Solution

  • During the calculations the value goes over 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.

    Try to replace int with long values. It will work with a greater value.

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

    With 14 and 2 as inputs the result is 91.

    If you want to have a correct result for big values you have to use a BigInteger that handle:

    Immutable arbitrary-precision integers