by Dinesh Thakur Category: Control Structures

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

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content







Popular Article