'Java code for calculating GCD and LCM of two numbers is working fine but not being accepted on one of the online platforms

below is my code for calculating gcd and lcm of two numbers. When i try with different test cases it works fine. But when i try to submit it on online platform it says wrong

package javapractice;
import java.util.*;
public class chef_gcdlcm {

    public static void main(String[] args) {
        try{
            Scanner input = new Scanner(System.in);
            long t = input.nextInt();
            long l,s,temp;
            while(t-->0){
                long A = input.nextLong();
                long B = input.nextLong();
                temp = 1;
                if(A>B){ l = A;
                 s = B;}
                else{ l = B;
                s = A;              
                }
                while(temp!=0){
                    temp = l%s;
                    if(temp!=0){
                        if(temp>s){l = temp;}
                        else{s = temp;}
                    }   
                }
                long gcd = (A*B)/s;
                System.out.println(s +" "+gcd);
            }
            input.close();
        }catch(Exception e){
            e.printStackTrace();
        }

    }

}


Solution 1:[1]

your code doesn't work, here's fixed;

package javapractice;
import java.util.*;
public class chef_gcdlcm {

  public static void main(String[] args) {
    try{
        Scanner input = new Scanner(System.in);
        long t = input.nextInt();
        long l,s,temp;
        while(t-->0){
            long A = input.nextLong();
            long B = input.nextLong();
            temp = 1;
            if(A>B){ 
               l = A;
               s = B;
            }else{ l = B;
               s = A;              
            }
            while (s != 0) {
              temp = l % s;
              if (temp > s) {
                 l = temp;
              } else {
                 l = s;
                 s = temp;
              }
            }
           long gcd = (A * B) / l;
           System.out.println(l + ":" + gcd);
        }
        input.close();
    }catch(Exception e){
        e.printStackTrace();
    }

  }

}

what you missed;

  1. you forgot set large to small (l=s) when temp is smaller than l.
  2. you don't have to check this: if(temp!=0) the while loop takes care of that.
  3. you should divide A*B to l, not to s at the end. s should come out 0.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 emrhzc