Write a Java method to find GCD and LCM of Two Numbers

Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..

import java.util.Scanner;
 
public class Javaexcercise 
{
    static int gcd(int x, int y)
    {
        int r=0, a, b;
        a = (x > y) ? x : y; 
        b = (x < y) ? x : y; 
 
        r = b;
        while(a % b != 0)
        {
            r = a % b;
            a = b;
            b = r;
        }
        return r;
    }
 
    static int lcm(int x, int y)
    {
        int a;
        a = (x > y) ? x : y; // a is greater number
        while(true)
        {
            if(a % x == 0 && a % y == 0)
                return a;
            ++a;
        }	
    }
 
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the two numbers: ");
        int x = input.nextInt();
        int y = input.nextInt();
 
        System.out.println("The GCD of two numbers is: " + gcd(x, y));
        System.out.println("The LCM of two numbers is: " + lcm(x, y));
        input.close();		
    }
}

Result

Write a Java method to find GCD and LCM of Two Numbers
Write a Java method to find GCD and LCM of Two Numbers

Leave a Comment