How to write a small graceful gcd function?



My small function works, but I have some questions. And I want to
listen to you on How it is implemented?

1. The function does not check if parameter x is larger or smaller than
parameter y.

2. Is it better to use unsigned int or unsigned long as the type of
parameters x and y? This change may remove the if statement.

More comments are still welcome.

/*The Greatest Common Divisor, GCD for short, of two positive integers
can be computed with Euclid's division algorithm. Let the given numbers
be a and b, a >= b. Euclid's division algorithm has the following
steps:
1. Compute the remainder c of dividing a by b.
2. If the remainder c is zero, b is the greatest common divisor.
3. If c is not zero, replace a with b and b with the remainder c. Go
back to step (1).

http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/gcd.html */

/*computes the GCD (Greatest Common Divisor) of positive integers x and
y with Euclid's algorithm. return the GCD, or -1 for failure. - jhl,
Jul 2006*/

int gcd(int x, int y){
if (x > 0 && y > 0){
while (x % y){
y = x + y;
x = y - x;
y = (y - x) % x;
}
} else {
y = -1; /*input invalid*/
}
return y;
}

lovecreatesbeauty

.



Relevant Pages

  • Re: How to write a small graceful gcd function?
    ... can be computed with Euclid's division algorithm. ... If the remainder c is zero, b is the greatest common divisor. ... int gcd (unsigned int a, ... /*The Greatest Common Divisor, GCD for short, of two positive integers ...
    (comp.lang.c)
  • Re: GCD(0,0)
    ... >>my point of view the G in GCD says it all. ... >>unless there's a strong reason. ... One of the things that is often done with the greatest common divisor ... would probably would have been adopted as the standard. ...
    (sci.math)
  • Re: Problem about gcd (help me :) )
    ... for the gcd to make sense you need that ideals ... We can define a greatest common divisor ... in which finitely generated ideals are principal ideals. ... i.e. elements that are unit multiples ...
    (sci.math)
  • Re: Analysis ToolPak Function in VBA is sloooow
    ... how does this old standby function I use for GCD stack up against it? ... Dim Remainder As Long ... Dim Num As Long ...
    (microsoft.public.excel.programming)
  • Re: Analysis ToolPak Function in VBA is sloooow
    ... the algorithm you offered is the best performer of all the solutions offered in this thread so far. ... Thus each scenario calls Totient(and therefore GCD) 1,000,000 times. ... Even after uncommenting the debug.print statements in ATP's native GCD function, timings were in the 80's. ... Dim Remainder As Long ...
    (microsoft.public.excel.programming)