Home Tutorial Java Core Find HCF of three numbers in Java Program

 
 

Share on Google+Share on Google+
Find HCF of three numbers in Java Program
Posted on: February 5, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to determine the HCF (Highest Common Factor) or GCD (Greatest Common Divisor) of three numbers.

Find HCF of three numbers in Java Program

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
Advertisement

Related Tags for Find HCF of three numbers in Java Program:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 5, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com