L
lovecreatesbeauty
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
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