by Dinesh Thakur

Algorithm for GCD of Two Numbers :

step 1:Read a, b

step 2: Repeat through step-5 while a not equals to 0

step 3: Set gcd=a

step 4: a=b%a

step 5:b=gcd

step 6: Print gcd

step 7: Exit

Here is the Java Example for GCD of Two Numbers:

import java.util.*;

public class GCDofTwoNumbers
{
                public static void main(String args[])
            {
                      int a,b,gcd;
                      a=b=gcd=0;
                      Scanner s=new Scanner(System.in);
                      system.out.println("Enter two nos.");
                      a=s.nextInt() ;
                      b=s.nextInt();
                      while(a!=0)
                            {
                                gcd=a;
                                a=b%a;
                                b=gcd;
                            }
                     System.out.println("GCD "+gcd);
             }
}

GCD of Two Numbers in Java Using While