GCD of Two Numbers in Java Using While
Menu
Turn Mobile View Off
You are here:  
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

Dinesh Thakur is a Technology Columinist and founder of Computer Notes and Technology Motivation. Turn Mobile View Off