GCD and LCM - Coder's point

Saturday, March 16, 2019

GCD and LCM

 import java.util.*;  
 class gcd_lcm  
 {  
    int gcd(int p, int q)  
   {  
     if(p==0)  
       return q;  
     else  
       return gcd(q%p,p);  
   }  
    int lcm(int a,int b)  
   {  
     if (a >= 0 && b >= 0) {  
       int gcd = lcm(-a, -b);  
       return (a * b) / gcd;  
     }  
     a = -a;  
     b = -b;  
     if (b == 0)  
       return a;  
     else  
       return lcm(-b, -(a%b));  
   }  
   void output(int n1,int n2)  
   {  
     int result1=gcd(n1,n2);  
     int result2=lcm(n1,n2);  
     System.out.println("GCD "+result1);  
      System.out.println("LCM "+result2);  
   }  
   public static void main()  
   {  
     gcd_lcm ob = new gcd_lcm();  
     Scanner in = new Scanner(System.in);  
     System.out.println("Enter any two numbers");  
     int n1=in.nextInt();  
     int n2=in.nextInt();  
     ob.output(n1,n2);  
   }  
 }  
OUTPUT:
Enter any two numbers
72
81
GCD 9
LCM 648

No comments:

Post a Comment