http://codeforces.com/contest/1278/problem/B for this my solution in giving TLE . can you help me out?

http://codeforces.com/contest/1278/problem/B

#include
#include
using namespace std;

int main()
{

int testcase=0;
cin>>testcase;
while(testcase--)
{
  long long a=0,b=0;
    cin>>a>>b;
    
    if (a==b)                 //if both are same
    cout<<0<<endl;
    else
    { 
       int flag=0;
       long long diff=llabs(a-b);  //finding the diffrence between the numbers
       long long length=0;
       if(a>b)
       length=a;
       else
       length=b;
       for(long long i=1;i<length;i++)
       {
       if(diff==(i*(i+1))/2)    // checking if the diffrence = sum of first i natural numbers
       { cout<<i<<endl;    // if so then all the operation will be performed on the one of 
                                                the number whichever is smaller
       flag=1;
       break;}}
       long long i=1,counter=0;
       while(a!=b && flag==0)    // if not so then operation will be performed on both the 
                                                       nos. on alternate time.
       {
           if(a<b)
           {
               if((i%2)!=0)
               a+=i;
               else
               b+=i;
               i++;
               counter++;
           }
           else
           {
               if((i%2)!=0)
               b+=i;
               else
               a+=i;
               i++;
               counter++;
               
           }
           
       }
       if(flag==0)
       {
           cout<<counter<<endl;
           flag=1;
       }
       
       
    }
    
}
return 0;

}

Please either format your code or link to your submission - the forum software has mangled it and it won’t compile! :slight_smile:

You’re using variable i in both while loop and for loop

Yes, so? Local scopes!

@phoenixsumit13 You’re actually looping from 1 to max(a,b) in the for loop; since a and b can be upto 10^9, your loop will be executed ~10^9 times and hence, you get a TLE!

ohk, so till what should i iterate my for loop? i am not able to figure it out!

http://codeforces.com/contest/1278/submission/67235158 .

1 Like

Why do you need the first loop actually?

https://codeforces.com/blog/entry/72330?#comment-566093

1 Like