Showing posts with label GCD in java. Show all posts
Showing posts with label GCD in java. Show all posts

Sunday, July 19, 2015

Greatest Common Divisor in Java

A simple program that will ask the user to enter two integer number and then our program will check and compute the Greatest Common Divisor or GCD of the two numbers given by our user.

I hope you will find my work useful and beneficial. If you have some questions about programming, about my work please send me an email at jakerpomperada@gmail.comand jakerpomperada@yahoo.com. People here in the Philippines can contact me at  my mobile number 09173084360.

Thank you very much and Happy Programming.


Sample Program Output


Program Listing

// gcd.java
// Programmer : Mr. Jake R. Pomperada, MAED-IT
// Date       : July 19, 2015
// Tools      : Netbeans 8.0.2
// Email      : jakerpomperada@yahoo.com and jakerpomperada@gmail.com

// Write a program that will check and determine the greatest common divisor
// of two numbers given by the user.


import java.util.Scanner; 

public class gcd {

    static int gcd(int m, int n, int d)
    { if (d==-1) 
        d = m>n ? n : m; 
    if (m%d==0 && n%d==0) 
        return d; 
    else 
        return gcd(m, n, d-1); 
    } 
    
    public static void main(String args[])
    { 
        
        Scanner input = new Scanner(System.in); 
        char ch;
    do {
      int m=0, n=0; 
      System.out.println();
      System.out.print("\t GREATEST COMMON DIVISOR SOLVER ");
      System.out.println("\n");
      System.out.print("Enter first number: "); 
      m = input.nextInt();
      System.out.print("Enter second number: "); 
      n = input.nextInt(); 
      System.out.print("The Greatest Common Divisor of "+m+" and "+n+" is "); 
      System.out.print(gcd(m, n, -1)+ "."); 
      System.out.println();
      System.out.print("\nDo you want to continue (Type y or n) : ");
      ch = input.next().charAt(0);                        
     } while (ch == 'Y'|| ch == 'y');  
      System.out.println();
      System.out.print("\t THANK YOU FOR USING THIS PROGRAM");
      System.out.println("\n\n");
    } 
}