Why is x *= (y1*y2*y3)/z1 not giving the same answer as x = x * (y1*y2*y3)/z1 in JAVA

Viewed 58

I am solving this on Leetcode and I ran across this error while submitting the answer for the question.

ans *= (N-i+1)/i; is not the same as ans = ans * (N-i+1)/i;

The value of answer for each iteration m=51 and n=9

  1. For ans *= (N-i+1)/i;
public int uniquePaths(int m, int n) 
    {
        double ans = 1;
        int N = m+n-2;
        int R = Math.min(n, m)-1;
        for(int i = 1; i <= R; i++)
        {
            ans *= (N-i+1)/i;
        }
        return (int)ans;
    }

The output for that is:

51/1
ans=58.0
52/2
ans=1624.0
53/3
ans=29232.0
54/4
ans=380016.0
55/5
ans=3800160.0
56/6
ans=3.040128E7
57/7
ans=2.1280896E8
58/8
ans=1.27685376E9
  1. For ans = ans * (N-i+1)/i;
public int uniquePaths(int m, int n) 
    {
        double ans = 1;
        int N = m+n-2;
        int R = Math.min(n, m)-1;
        for(int i = 1; i <= R; i++)
        {
            System.out.println((N-R+i)+"/"+i);
            ans = ans * (N-i+1)/i;
            System.out.println("ans="+ans);
        }
        return (int)ans;
    }
51/1
ans=58.0
52/2
ans=1653.0
53/3
ans=30856.0
54/4
ans=424270.0
55/5
ans=4582116.0
56/6
ans=4.0475358E7
57/7
ans=3.00674088E8
58/8
ans=1.916797311E9

When the values being multiplied are the same, why am I getting two different answers?

1 Answers

In ans *= (N-i+1)/i;, (N-i+1)/i is evaluated first. All the operands are ints, so integer division with truncation is performed. The truncated result is then used to update the value of ans.

With ans = ans * (N-i+1)/i;, the first operand to the multiplication operator is a double, so the result is a double. That result is divided by i and floating-point division is performed.

Related