Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

can someone please explain this c++ behaviour

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading