Look at this function:
int c(int n,int k) {
if (n<0 || k<0 || n<k) {
return 0;
}
int c=1,p=n-k,i=1;
while (n>p) {
c = c * n/i++; // <<<
n--;
}
return c;
}
when I change c=c*n/i++
to c*=n/i++
function don't work correctly. for example c(4,2)=4 (=6 true) I traced with:1.i++ 2./ 3.*= and all other possibilities but no answer. why?
edit: this is not my question as people know. I asked why compiler answer c(4,2)=4
when c*=n/i++
. I traced */++, *++/, /*++, /++*, ++*/, ++/*
but answer is not 4 at all. what is compiler's logic?(sorry for bad English)
In the case of
c = c * n / i++;
You first multiply c
and n
, then divide it by i
, and lastly i
is increased.
When you do
c *= n / i++;
You first to the division and increase of i
, then do the multiplication.
In other words:
c = c * n / i++;
is equal to
c = (c * n) / i++;
While
c *= n / i++;
is equal to
c = c * (n / i++);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With