i am getting wrong answer with :
int N = 6;
int r = 3;
long result = 1;
for(int i=1;i<=r;++i){
result *= (N-r+i)/(i);
}
output: 16
But this one is giving the correct answer:
for(int i=1;i<=r;++i){
result *= N-r+i;
result /= i;
}
output: 20
please explain the behaviour
>Solution :
The first code snipped you are multiplying the current value of result by ((N-r+i)/(i)). Which is equal to saying result = result * ((N-r+i)/(i));.
In the second code snipped you are multiplying the current value of result by (N-r+i) then after the value of result gets updated. You then take the updated result and then dividing it by i. You are performing the operation result = (result * (N-r+i)) / i;
So in the first code snipped you are updating result once and in the second code snipped you are updating result twice.