Guest User

GCD / HCF in Java

a guest
Oct 29th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. /**
  2.  * This program inputs two numbers and finds their greatest common divisor or the highest common factor (GCD / HCF).
  3.  */
  4. import java.util.Scanner;
  5. public class Find_GCD
  6. {
  7.     static int findGCD(int num1, int num2)
  8.     {
  9.         int i;
  10.         int smaller=Math.min(num1, num2); //Finding the smaller number since the GCD / HCF itself cannot be greater than any of the numbers.
  11.         for(i=smaller;i>0;i--) //Decreasing from the smaller number.
  12.         {
  13.             if(num1%i==0 && num2%i==0) //Checking whether the number is a factor of both the numbers or not.
  14.             {
  15.                 break; //Found it!
  16.             }
  17.         }
  18.         return i;
  19.     }
  20.     public static void main(String[] args)
  21.     {
  22.         Scanner sc=new Scanner(System.in);
  23.         System.out.println("Please enter the first number: ");
  24.         int num1=sc.nextInt();
  25.         System.out.println("Please enter the second number: ");
  26.         int num2=sc.nextInt();
  27.         int gcd=findGCD(num1,num2);
  28.         System.out.println("The greatest common divisor (gcd) of "+num1+" and "+num2+" is "+gcd+".");
  29.        
  30.         sc.close();
  31.     }
  32. }
Add Comment
Please, Sign In to add comment