Search code examples
javagreatest-common-divisorlcm

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

  • It isn't necessary to do the swapping and comparing. If necessary, the values will be corrected after the first iteration.

    Consider l = 24 and s = 36
    save = s;    save is 36
    l %= s;      l is still 24 
    s = l;       s is now 24
    l = save     l is now 36
    
    

    Modified code

    try {
        Scanner input = new Scanner(System.in);
        long t = input.nextInt();
        long l, s, temp;
        while (t-- > 0) {
            l = input.nextLong();
            s = input.nextLong();
            long A = s;
            long B = l;
            // doesn't matter which is larger.  It will be corrected
            // after the first iteration.
            while (s > 0) {
                 temp = s; 
                 l %= s; 
                 s = l;
                 l = temp;
            }
            long lcm =  (A / l) * B; // prevents overflow
            System.out.println(l + " " + lcm);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    Note: It is not necessary, useful, and in general bad practice to close the scanner when it was created with System.in. This is because that also closes that input stream which will no longer be available for the duration of the program.