Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This program inputs two numbers and finds their greatest common divisor or the highest common factor (GCD / HCF).
- */
- import java.util.Scanner;
- public class Find_GCD
- {
- static int findGCD(int num1, int num2)
- {
- int i;
- int smaller=Math.min(num1, num2); //Finding the smaller number since the GCD / HCF itself cannot be greater than any of the numbers.
- for(i=smaller;i>0;i--) //Decreasing from the smaller number.
- {
- if(num1%i==0 && num2%i==0) //Checking whether the number is a factor of both the numbers or not.
- {
- break; //Found it!
- }
- }
- return i;
- }
- public static void main(String[] args)
- {
- Scanner sc=new Scanner(System.in);
- System.out.println("Please enter the first number: ");
- int num1=sc.nextInt();
- System.out.println("Please enter the second number: ");
- int num2=sc.nextInt();
- int gcd=findGCD(num1,num2);
- System.out.println("The greatest common divisor (gcd) of "+num1+" and "+num2+" is "+gcd+".");
- sc.close();
- }
- }
Add Comment
Please, Sign In to add comment