Source of GreatestCommonDivisor.java


  1: //GreatestCommonDivisor.java

  3: public class GreatestCommonDivisor
  4: {
  5:     public static void main(String[] args)
  6:     {
  7:         System.out.println("\nTesting gcd() ...");
  8:         System.out.println(gcd(12, 30));
  9:         System.out.println();
 10:         System.out.println(gcd(30, 12));
 11:         System.out.println();
 12:         System.out.println(gcd(12345, 54321));
 13:         System.out.println();
 14:         System.out.println(gcd(30, 0));
 15:         System.out.println();
 16:         System.out.println(gcd(0, 30));
 17:         System.out.println();
 18:         System.out.println(gcd(34, 187));
 19:         System.out.println();
 20:         System.out.println(gcd(7777, 555));
 21:         System.out.println();
 22:         System.out.println(gcd(97, 43));
 23:     }

 25:     //Computes and returns the greatest common divisor of a and b.
 26:     //Assumes a, b >= 0 and at least one of them is > 0.
 27:     public static int gcd
 28:     (
 29:         int a,
 30:         int b
 31:     )
 32:     {
 33:         //Inserted one line of "tracing code":
 34:         System.out.println("a: " + a + "  b: " + b);
 35:         if (b == 0)
 36:             return a;
 37:         else
 38:             return gcd(b, a % b);
 39:     }
 40: }