In this article, we are going to find the GCD(Greatest Common Divisor) of two numbers using java code.
Example:- if a=10(first number), b=15(second number) then GCD of a and b will be 5.
Steps:-
- Take the input for a and b from the user using scanner.
- Find the minimum of a and b and store in a variable x.
- Take a variable ans and initialize it with 1.
- Run a loop for i=1 to i<=x.
- check if a and b are divisible by i, then ans=i.
Java code to find GCD of two numbers.
package gangforcode;
import java.util.Scanner;
public class GCD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
int a=sc.nextInt();
System.out.println("Enter second number");
int b=sc.nextInt();
int ans=1;
int x=Math.min(a, b);
for(int i=1;i<=x;i++)
{
if(a%i==0 && b%i==0) {
ans=i;
}}
System.out.print(ans);
}
}
Output:-
You can use the same logic to find the GCD of two numbers using other programming languages like C, C++,Python, etc.