GCD of Two Numbers in Java

GCD of Two Numbers in Java for beginners. The greatest common divisor is the biggest number that divides two or more numbers entirely. GCD is an abbreviation. It’s also known as the GCF or the HCF. 

The greatest common divisor of two or more integers is returned by the GCD function. 

The largest positive integer that divides the numbers without leaving a residual is known as the greatest common divisor. 

In other words, the greatest number that evenly divides all other numbers. These are major reasons for gcd recursion in java important for beginner in programming.

GCD of Two Numbers in Java

Greatest Common Divisor is another name for HCF. Express each number as a product of prime numbers to get the HCF of two or more numbers.

When two integers have the same greatest common divisor, their absolute values have the same gcd. 

As a result, the function can simply replace negative numbers with their positive negatives. GCD of two numbers for beginners.

If Else Statement to Execute GCD in Java

In Java, the if statement is used to execute a block of code if a condition is true. If a condition evaluates to false, the if…else statement is used alongside an if statement to run code. The if else if phrase can also be used to test multiple conditions. 

Decision Making in Java facilitates the creation of decision-driven statements and the execution of a specific set of code in response to specified situations. If a condition is true, the if statement will execute a block of statements; if the condition is false, it will not. Using this method we can execute the gcd recursion in java.

Return Statement in Java Program

The control of the program is returned to the method’s caller when a return statement is used. Every Java method declares a return type, which is required for all Java methods. A primitive type like as int, float, or double, a reference type, or a void type returns nothing.

GCD Using Recursion in Java and How Recursion Works

In Java, recursion is a fundamental programming approach in which a method calls itself to solve a problem. Recursive is a method that employs this strategy. When the recursive method reaches the end condition, it should cease calling itself.

Not Equal to Function

The == and!= operators should not be used to compare two strings in Java. These operators are actually reference tests, and because multiple String objects can represent the same String, they are likely to return an incorrect result. 

public class Main 
{
public static void main(String[] args) 
{
int a = 200, b = 70;
int hcf = hcf(a, b);
System.out.printf("G.C.D of %d and %d is %d", a, b, hcf);
}
public static int hcf(int a, int b)
{
if (b != 0)
return hcf(b, a % b);
else
return a;
}
}

Output:

G.C.D of 200 and 70 is 10