FIND GCD in java

FIND GCD in java

Find GCD(Greatest Common Divisor) of two numbers using Euclidean Algorithm.

Input

Contains two integers a and b of which gcd is to be found.

Output

Print a single integer denoting the gcd of two numbers.

Constraints

0<=a,b<=10^6

Sample Input

658 640

Sample Output

2

Solution:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      int n1 = sc.nextInt();
      int n2 = sc.nextInt();
      
      int index=0;
      for(int i=1;i<=n1 && i<=n2;i++)
        {
          if(n1%i==0 && n2%i==0)
          {
            index=i;
          }
        }

      System.out.println(index);
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *