DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Greatest Common Denominator Function

07.04.2007
| 4966 views |
  • submit to reddit
        This function returns the greatest common denominator (GCD) of its arguments.
int gcd(int x, int y) {
 int a, b;
 if (x<y) {a = y; b = x; }
 else if (x>y) {a = x; b = y; }
 else {return x; }
 do {
  int r = a % b;
  a = b;
  b = r;
 } while (b != 0);
 return a;
}