Java Program - Find Greatest common Divisor

Source code to Find the Greatest Common Divisor program in Java.

// Find the Greatest Common Divisor from the two numbers provided by the user in Java. 

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[]) {

     int m, n;
     Scanner in = new Scanner(System.in);
     System.out.print("Enter first number: ");
     m = in.nextInt();
     System.out.print("Enter second number: ");
     n = in.nextInt();
     System.out.print("GCD of "+m+" & "+n+" is ");
     System.out.print(gcd(m, n, -1));
   }

}

Output of the Java program to find (GCD) greatest common divisor:


0 comments:

Post a Comment