MARCHA2 doubt

Here is my first solution:

This gave me two WAs on testcase #3 and #5.

I saw some of codes written by others, and the only difference was the if(stem<0)break;

This is the modified solution that got AC:

I didnt understand what was wrong in my first code. Why do we need that if and break.

I would really appreciate help on this. I am going crazy with this.



This is the difference between the 2 codes.i will tell you why this condition is of significant importance.

Let us take this example test case: 



(all inputs are equal to 2)

Now in such a case ,the condition (old<0) will be true in the first iteration itself.if this condition was present in the code we would play safe by breaking from the loop.if not ,then all the 10^6 iterations will be performed .Since old<0 in the 1st iteration itself, in the subsequent iterations the negative value of old will increase and in in each step we would be multiplying the result by 2. And ,hence after 10^6 iterations the value of old will have something like more than 10^6 digits which i think will not fit in any int data type, and hence will result in overflow.

  If overflow occurs some random garbage value will be stored in variable"old" after 10^6 iterations .But there is a slight possibility of this value being 0 , and in such a case your output would be "Yes",but the correct answer is "No",which i think explains why the second code got accepted while the first did not.if you find my post helpful upvote and mark it as accepted answer.CHEERS HAPPY CODING :)
1 Like

Thanks. :smiley: The test case helped a lot :DD