Search code examples
javafactorialgreatest-common-divisor

How to write a function that implements Euclid's Algorithm for computing the greatest common divisor ( m,n)?


I'm trying to add the gcd() function to the NumericFunctions class and include code in main to compute gcd(m,n).

However, I keep getting an error:

Exception in thread "main" java.lang.StackOverflowError
    at NumericFunctions.gcd(NumericFunctions.java:14)

Source code:

public class NumericFunctions {

   public static long factorial(int n) {

      long result = 1;

      for (int i = 2; i <= n; i++) {

         result *= i;
      }
      return result;
   }

   public static int gcd (int n, int m) {

      if ((m % n) == 0) 

         return n;

      else

         return gcd(n, m % n);
}

     public static void main(String[] args) {

         for (int n = 1; n <= 10; n++)

            for (int m = 1; m <= 10; m++){

               System.out.println(gcd(n,m));

               System.out.println(" ");

               System.out.println(factorial(n));

            }
      }
}

Solution

  • Check out the following corrections in gcd() method:

    public static int gcd (int n, int m) {
        if ((n % m) == 0)
            return m; // <-- first correction
        else
            return gcd(m, n % m);  // <-- second correction
    }