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
- 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
- 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?