Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the GCD of two numbers without using divison or mod operator?

I want to find GCD of two numbers but without using division or mod operator. one obvious way would be to write own mod function like this:

enter code here
int mod(int a, int b)
{
   while(a>b)
       a-=b;

return a;
}

and then use this function in the euclid algorithm. Any other way ??

like image 207
jairaj Avatar asked Dec 06 '25 08:12

jairaj


2 Answers

You can use the substraction based version of euclidean algorithm up front:

function gcd(a, b)
    if a = 0
       return b
    while b ≠ 0
        if a > b
           a := a − b
        else
           b := b − a
    return a
like image 138
amit Avatar answered Dec 08 '25 21:12

amit


What you are looking for is the Binary GCD algorithm:

public class BinaryGCD {

    public static int gcd(int p, int q) {
        if (q == 0) return p;
        if (p == 0) return q;

        // p and q even
        if ((p & 1) == 0 && (q & 1) == 0) return gcd(p >> 1, q >> 1) << 1;

        // p is even, q is odd
        else if ((p & 1) == 0) return gcd(p >> 1, q);

        // p is odd, q is even
        else if ((q & 1) == 0) return gcd(p, q >> 1);

        // p and q odd, p >= q
        else if (p >= q) return gcd((p-q) >> 1, q);

        // p and q odd, p < q
        else return gcd(p, (q-p) >> 1);
    }

    public static void main(String[] args) {
        int p = Integer.parseInt(args[0]);
        int q = Integer.parseInt(args[1]);
        System.out.println("gcd(" + p + ", " + q + ") = " + gcd(p, q));
    }
}

Source: http://en.wikipedia.org/wiki/Binary_GCD_algorithm

like image 40
Bobb Dizzles Avatar answered Dec 08 '25 21:12

Bobb Dizzles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!