In this tutorial, we will write a Java program to find out the GCD of two numbers.
The GCD (Greatest Common Divisor) of two numbers is the largest positive integer number that divides both the numbers without leaving any remainder. For example. GCD of 30 and 45 is 15. GCD also is known as HCF (Highest Common Factor).
The GCD (Greatest Common Divisor) of two numbers is the largest positive integer number that divides both the numbers without leaving any remainder. For example. GCD of 30 and 45 is 15. GCD also is known as HCF (Highest Common Factor).
Java Program to Find GCD of Two Numbers
package com.javaguides.java.tutorial;
import java.util.Scanner;
/**
* Java Program to Find GCD of Two Numbers
*
* @author https://www.sourcecodeexamples.net/
*
*/
public class JavaProgram {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int num1, num2;
System.out.print("Enter first number:");
num1 = (int) scanner.nextInt();
System.out.print("Enter second number:");
num2 = (int) scanner.nextInt();
// closing the scanner to avoid memory leaks
scanner.close();
while (num1 != num2) {
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
}
// displaying the result
System.out.printf("GCD of given numbers is: %d", num2);
}
}
}
Output:
Enter first number:10
Enter second number:20
GCD of given numbers is: 10
Related Java Programs
- Java program to calculate the area of Triangle
- Java Program to Calculate Area of Square
- Java Program to Calculate Area of Rectangle
- Java Program to find the Smallest of three numbers using Ternary Operator
- Java Program to Find Largest of Three Numbers
- Java Program to Find GCD of Two Numbers
- Java Program to Check Armstrong Number
- Java Program to Generate Random Number
- Java Program to Check if Number is Positive or Negative
- Java program to check prime number
- Java Program to Calculate Simple Interest
- Java Program to Swap Two Numbers Without using a Temporary Variable
- Java Program to Swap Two Numbers
- Java Program to Find ASCII Value of a Character
- Java Program to Check Whether an Alphabet is Vowel or Consonant
- Java Program to Check Leap Year
- Java Program to Multiply Two Numbers
- Java Program to Check Even or Odd Number
- Java Program to Add Two Numbers
- Java Program to Swap Two Strings Without Using Third Variable
- Java Program to Swap Two Strings with Third Variable
- How to Get All Digits from String in Java
- Find Duplicate Number in Array in Java
- How to Get Current Working Directory in Java?
- Check Palindrome String in Java
- Java Program to Create Pyramid Of Numbers
Comments
Post a Comment