Write a program to input two positive
integers and find its HCF (Highest
Common Factor) using a user-defined
method with the following prototype:
public static int gcd(int a, int b)
Answers
Explanation:
Let's use Java
code:-
// Java program to find GCD of two numbers
class Test
{
// Recursive function to return gcd of a and b
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// Driver method
public static void main(String[] args)
{
int a = 98, b = 56;
System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
}
}
Answer:
Used import method:
import java.util.*;
public class Brainly
{
static void main()
{
Scanner sc=new Scanner(System.in);
int i,a,b;
System.out.println("Enter 2 integers:");
a=sc.nextInt();
b=sc.nextInt();
for(i=a;i>=1;i--)
{
if(a%i==0 && b%i==0)
break;
}
System.out.println("H.C.F.="+i);
}
}