next up previous
Next: GCD: using the method Up: Unit 06 Previous: GCD: using the method

GCD: admissible values for the arguments

What happens in the previous algorithm in the following cases:

Hence, if we want to take into account that the method could be called with arbitrary integer values for the parameters, it is necessary to insert a suitable test.

public static int greatestCommonDivisor(int x, int y) {
  if ((x > 0) && (y > 0)) {
    while (x != y)
      if (x > y)
        x = x - y;
      else              // this means that y > x
        y = y - x;
    return x;
  } else
    System.out.println("wrong parameters");
}


next up previous
Next: GCD: using the method Up: Unit 06 Previous: GCD: using the method