Write a Program in Java to input 2 numbers and find their Highest Common Factor (HCF).
Note: If the 2 numbers are 54 and 24, then the divisors (factors) of 54 are: 1, 2, 3, 6, 9, 18, 27, 54.
Similarly the divisors (factors) of 24 are: 1, 2, 3, 4, 6, 8, 12, 24.
The numbers that these two lists share in common are the common divisors (factors) of 54 and 24: 1, 2, 3, 6.
The greatest (highest) of these is 6. That is the greatest common divisor or the highest common factor of 54 and 24.
import java.io.*;class Hcf { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the First no : "); int n1=Integer.parseInt(br.readLine()); System.out.print("Enter the Second no : "); int n2=Integer.parseInt(br.readLine()); int hcf=0; int min = Math.min(n1,n2); for(int i=min; i >= 1; i--) { if(n1%i == 0 && n2%i == 0) { hcf = i; break; } } System.out.print("\nThe hcf of "+n1+" and "+n2+" = "+hcf); } }
Output:
Enter the First no : 54
Enter the Second no : 24
The hcf of 54 and 24 = 6
Nice article for find hcf for two number .one more way to find hfc and lcm visit HCF and LCM of two number
ReplyDelete