How to encounter the Time Limit Exceeded(TLE) in the program

#include <stdio.h>

int main(void) {
long int t,i ,a,b;
scanf("%ld",&t);
for(i=1;i<=t;i++)
{
scanf("%ld%ld\n",&a,&b);
while(a!=b&&a!=0&&b!=0)
{
if(a>b)
a=a-b;
else
b=b-a;

    }
    
    printf("%ld\n",a+b);
}


return 0;

}

The scanf statement is incorrent for your purpose. It should be scanf("%ld %ld", &a, &b); instead of scanf("%ld%ld\n",&a,&b);.

1 Like
1 Like

The result of while loop will be the HCF of the two numbers.
Just try mathematical approach to find HCF of a and b
while(b>0){
temp=b;
b=a%temp;
a=temp;
}

then print 2*a.

1 Like

What are you trying to solve.
It looks like…
Lets say a=5,b=2

5-2=3 (a=3)
3-2=1 (a=1)
2-1=1 (b=1)

now a=b=1 so it should print 2.

You can do it like this

  public static void main (String[]args) throws java.lang.Exception
  {
    // your code goes here
    Scanner in = new Scanner (System.in);
    int t = in.nextInt ();
    for (int i = 0; i < t; i++)
      {
        int a = in.nextInt();
        int b = in.nextInt();
        
        while (a!=b && a!=0 && b!=0)
        {
            
            if (a>b && a%b!=0) a-=(a/b)*b;
            else if (a>b) a-=b;
            else if (b>a && b%a!=0) b-=(b/a)*a;
            else if (b>a) b-=a;
            
            
        }
        System.out.println(a+b);
      }
  }
1 Like

can you send the question link

LOL. An example based on an Anime Series “Seven Deadly Sins”. Crazy!

Just code something incredibly inefficient and you will encounter TLE in no time.

2 Likes

can you send link or problem code?