High School Physics

Java program to find HCF (highest common factor) of 2 numbers

Let’s see how to write a Java program to find the HCF (highest common factor) of 2 numbers.

Here is a Java program that accepts 2 numbers and finds the greatest common divisor or HCF (highest common factor) of those numbers.

Java Program to find HCF

import java.util.Scanner;
public class HCF {

public static void main(String args[]){
int a, b, i, hcf = 0;
Scanner sc = new Scanner(;
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);

See also  Java program - class hierarchy using base class and child class
Scroll to top