- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to find the GCD or HCF of two numbers
An H.C.F or Highest Common Factor, is the largest common factor of two or more values.
For example factors of 12 and 16 are −
12 → 1, 2, 3, 4, 6, 12 16 → 1, 2, 4, 8, 16
The common factors are 1, 2, 4 and the highest common factor is 4.
Algorithm
Define two variables - A, B
Set loop from 1 to max of A, B
Check if both are completely divided by same loop number, if yes, store it
Display the stored number is HCF
Example
import java.util.Scanner; public class GCDOfTwoNumbers { public static void main(String args[]){ int a, b, i, hcf = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter first number :: "); a = sc.nextInt(); System.out.println("Enter second number :: "); b = sc.nextInt(); for(i = 1; i <= a || i <= b; i++) { if( a%i == 0 && b%i == 0 ) hcf = i; } System.out.println("HCF of given two numbers is ::"+hcf); } }
Output
Enter first number :: 625 Enter second number :: 125 HCF of given two numbers is ::125
- Related Articles
- Program to find GCD or HCF of two numbers in C++
- Program to find GCD or HCF of two numbers using Middle School Procedure in C++
- Java Program to Find GCD of two Numbers
- Java Program for GCD of more than two (or array) numbers
- Haskell program to find the gcd of two numbers
- Swift Program to Find GCD of two Numbers
- Kotlin Program to Find GCD of two Numbers
- How to Find HCF or GCD using Python?
- Find GCD of two numbers
- Haskell Program to find the GCD of two given numbers using recursion
- Swift program to find the GCD of two given numbers using recursion
- Python Program for GCD of more than two (or array) numbers
- GCD of more than two (or array) numbers in Python Program
- C++ Program for GCD of more than two (or array) numbers?
- C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm

Advertisements