In this program, you’ll learn how to find GCD of two numbers in Java Algorithm. In this program, user is asked to enter two integers. These two integers are stored in variables firstNumber and secondNumber respectively.
Then, Program codes are written as following
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class JavaExamples { public static void main(String[] args) { Scanner reader = new Scanner(System.in); int firstNumber, secondNumber; System.out.print("Enter first number: "); firstNumber= reader.nextInt(); System.out.print("Enter second number: "); secondNumber= reader.nextInt(); int gcd = 1; for(int i = 1; i <= firstNumber && i <= secondNumber; ++i) { // Checks if i is factor of both integers if(firstNumber % i==0 && secondNumber % i==0) gcd = i; } System.out.printf("G.C.D of %d and %d is %d \n", firstNumber, secondNumber, gcd); } } |
Output: