Write a program to design a function hcf(int , int) which accept two numbers and return
their HCF. Call the function from main to display the HCF.
Question 6:
Answers
public class HCF {
static int hcf(int numOne, int numTwo) {
numOne = Math.abs(numOne);
numTwo = Math.abs(numTwo);
while (numOne != numTwo) {
if (numOne > numTwo)
numOne -= numTwo;
else
numTwo -= numOne;
}
return numOne;
}
public static void main(String[ ] args) {
int numOne = 45, numTwo = 5;
System.out.printf("HCF of %d and %d is %d", numOne, numTwo, hcf(numOne, numTwo));
}
}
Question:-
Write a program to design a function hcf(int, int) which accept two numbers and return their HCF. Call the function from main to display the HCF.
Code:-
import java.util.*;
public class HCF
{
static int hcf(int a, int b)
{
while(b!=0)
{
r=a%b;
a=b;
b=r;
}
return a;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
int a=sc.nextInt();
System.out.print("Enter the second number: ");
int b=sc.nextInt();
System.out.println("HCF of two numbers is: "+hcf(a, b));
}
}