jaigurudev's blog

By jaigurudev, 10 years ago, In English

Can any help with an algo that is fast enough to calculate the gcd of two positive numbers. I think one good approach will be to use __gcd of C++ but it is inbuilt, i want to create my own function. Please help...

  • Vote: I like it
  • -16
  • Vote: I do not like it

| Write comment?
»
10 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

a recursive method will work perfectly

int gcd(int a, int b) { if (a == 0) return b; else return gcd (b % a, a); }

»
10 years ago, # |
  Vote: I like it 0 Vote: I do not like it
»
10 years ago, # |
  Vote: I like it +5 Vote: I do not like it
»
10 months ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

Euclidean Algorithm is the most efficient for calculating GCD.

Method 1(Recursive) :

int gcd_number(int a, int b) {
    if (b==0) {
        return a;
    }
    else {
        return gcd_number(b, a-b*floor(a/b));
    }
}

Method 2 (Recursive) :

int gcd_number(int a, int b) {
    if (a==0) {
        return b;
    }
    return gcd_number(b%a, a);
}