Showing posts with label lcm and gcd in java. Show all posts
Showing posts with label lcm and gcd in java. Show all posts

Sunday, February 19, 2017

GCD and LCM of two integers using Euclids' Algorithm in Java


A simple program that I wrote using Java to solve the GCD and LCM of a given number of the user.

Add me at Facebook my address is jakerpomperada@gmail.com and jakerpomperada@yahoo.com

My email address are the following jakerpomperada@gmail.com and jakerpomperada@yahoo.com

My mobile number here in the Philippines is 09173084360.




Sample Program Output


Program Listing

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gcd_lcm;


import java.util.Scanner;

/**
 *
 * @authors Jake R. Pomperada and  Jacob Samuel F. Pomperada
 * Date : February 19, 2017  Sunday
 * Language : Java
 * IDE     : NetBeans
 */
public class gcd_lcm {

    /**
     * @param args the command line arguments
     */
    
    void display()
    {
       int num1=0, num2=0, gcd=0, lcm=0, remainder=0, numerator=0, denominator=0;

        Scanner s = new Scanner(System.in);
     
        System.out.println();
        System.out.println("===  GCD and LCM of two integers using Euclids' Algorithm in Java === ");
        System.out.println();
      
         System.out.print("Enter First Value : ");
         num1 = s.nextInt();
            
         System.out.print("Enter Second Value : ");
         num2 = s.nextInt();
                 
        if (num1 > num2)

        {
        numerator = num1;
        denominator = num2;
        }
    else

       {
        numerator = num2;
        denominator = num1;
       }

    remainder = numerator % denominator;

    while (remainder != 0)

    {

        numerator   = denominator;

        denominator = remainder;

        remainder   = numerator % denominator;

    }

    gcd = denominator;

    lcm = num1 * num2 / gcd;
  
        System.out.println();
        System.out.println("===== DISPLAY RESULTS ======");
        System.out.println();
        System.out.println("The GCD of " + num1 + " and "
                           + num2 + " is " + gcd + ".");

        System.out.println("The LCM of " + num1 + " and "
                           + num2 + " is " + lcm + ".");

        System.out.println();
        System.out.println("===== END OF PROGRAM ======");
        System.out.println();
    }
    
    public static void main(String[] args)
      {
        // TODO code application logic here
      gcd_lcm demo  = new gcd_lcm();
      demo.display();
            
    }
    
}