In this java tutorial section, you will learn how to determine the HCF (Highest Common Factor) or GCD (Greatest Common Divisor) of three numbers. As you already know that HCF or GCD is the largest positive integer that can exactly divide each one of the number.
Suppose there are three numbers 4,8 and 12.
Factors of 4=1,2,4
Factors of 8=1,2,4,8
Factors of 12=1,2,3,4,6,12
Here 4 is the highest number that can exactly divide both 4 and 8 and 12, so 4 is the HCF of 4,8 and 12.
Here is the code:
import java.util.*;
public class HCFOFNumbers {
public static int hcf(int a, int b) {
if (b == 0)
return a;
else
return hcf(b, a % b);
}
public static int hcf(int a, int b, int c) {
return hcf(hcf(a, b), c);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Number 1: ");
int num1 = input.nextInt();
System.out.print("Enter Number 2: ");
int num2 = input.nextInt();
System.out.print("Enter Number 3: ");
int num3 = input.nextInt();
int hcfOfNumbers = HCFOFNumbers.hcf(num1, num2, num3);
System.out.println("HCF of three numbers " + num1 + "," + num2
+ " and " + num3 + " is: " + hcfOfNumbers);
}
}
Output:
| Enter Number 1: 7 Enter Number 2: 14 Enter Number 3: 28 HCF of three numbers 7,14 and 28 is: 7 |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.