Greatest common Divisor asking is this logic is correct?

42 views Asked by At

The correct and most efficient way to calculate Greatest common divisor its common question to ask in beginner coding interview

void function that returns nothing just taking 2 parameter from user and calculate its greatest common divisor.


    public static void Greatest_Common_Divisor(int a, int b){
        int gcd=1,i=2;

        while(true){
            if(a%i==0 && b%i==0){ // checking both the number is divisible by i
                gcd=gcd*i;        // if yes multiply gcd value
                a=a/i;
                b=b/i;
                if(a%i!=0 || b%i!=0){ // divisible incrementing i by 1
                    i++;
                }
            }
            else{
                System.out.println("Greatest Common Divisor :"+gcd);
                break;
            }
        }
    }

0

There are 0 answers