Read in your tongue here..

Saturday, April 19, 2014

Calculating GCD of two numbers using Java

class GCD{
        public static void main(String args[])
        {
                int gcd=1;
                int n1=Integer.parseInt(args[0]);
                int n2=Integer.parseInt(args[1]);
                int num=n1<n2?n1:n2;
                if(num==1)
                        System.out.println("GCD of "+n1+" and "+n2+"="+gcd);
                else       
                {
                        for(int i=2;i<=num/2;i++)
                                if(n1%i==0&&n2%i==0)
                                        gcd=i;
                        System.out.println("GCD of "+n1+" and "+n2+"="+gcd);
                }
        }
}

No comments:

Post a Comment