Basic Maths C++ Solution


#define ll long long int

int Solution::solve(int A) {
if(A==0) return 0;
int i=1;
ll sum=0;
if(sum==A) return i;
if(sum>A) break;

ll cur=sum-A;
if(cur%2==0) return i;
if((cur+i+1)%2==0) return  i+1;
return i+2;



Can you please explain the logic behind the last 2 if conditions of returning either i, i+1, i+2 !?


you can observe that cur will be less than i…now if we change the sign of any one of the terms added in sum to -ve the sum will get reduced by an even amount…so if cur is even then we can remove some no x less than i to make it a…but if not then if i is even i+1 will be odd…now adding i+1 to cur will result in even cur…and again we can remove some no less than equal to i to make it x…but if i is odd then i+2 can only make the cur even…