How to find GCD and LCM of two numbers in java

In this post, we will see how to find Greatest common divisor(GCD) and Least Common Multiple(LCM) in java.
GCD is calculated using Euclidean algorithm and LCM is calculated using reduction by GCD

Eucid algo for calculating GCD is:

Lets say , there are two numbers , a and b so
GCD of two numbers = GCD (b,a%b) and GCD(a,0)=a

LCM can be calculated using reduction by GCD :

LCM of two numbers a and b = a * b/GCD(a,b)

Java program :

package org.arpit.java2blog;

import java.util.Scanner;

public class GCDLCMMain {

 /**
  * @author arpit mandliya
  */
 public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter the two numbers: ");

        int number1 = input.nextInt();
        int number2 = input.nextInt();


        System.out.println("The GCD of two numbers is: " + gcd(number1, number2));
        System.out.println("The LCM of two numbers is: " + lcm(number1, number2));

        input.close();  

 }

 // Using Eucid algorithm for calculating gcd
 public static int gcd(int a,int b)
 {
  if(b==0)
   return a;
  else
   return gcd(b,a%b);
 }
 
 public static int lcm(int a,int b)
 {
  return a*b/(gcd(a,b));
 }
 
 
}

When you run above program, you will get following output:
Enter the two numbers: 
4
6
The GCD of two numbers is: 2
The LCM of two numbers is: 12
 

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012