Java finds the greatest common divisor and least common multiple of two positive integers

  • 2020-06-12 09:03:01
  • OfStack

Enter two positive integers m and n to find their maximum common divisor and least common multiple.

Program analysis: the use of rolling method.

Maximum common divisor:


public class CommonDivisor{
  public static void main(String args[])
  {
    commonDivisor(24,32);
  }
  static int commonDivisor(int M, int N)
  {
    if(N<0||M<0)
    {
      System.out.println("ERROR!");
      return -1;
    }
    if(N==0)
    {
      System.out.println("the biggest common divisor is :"+M);
      return M;
    }
    return commonDivisor(N,M%N);
  }
}

Least common multiple and greatest common divisor:


import java.util.Scanner;
public class CandC
{
  // The next method is to find the greatest common divisor 
  public static int gcd(int m, int n)
  {
    while (true)
    {
      if ((m = m % n) == 0)
        return n;
      if ((n = n % m) == 0)
        return m;
    }
  }
  public static void main(String args[]) throws Exception
  {
    // Get the input value 
    //Scanner chin = new Scanner(System.in);
    //int a = chin.nextInt(), b = chin.nextInt();
    int a=23; int b=32;
    int c = gcd(a, b);
    System.out.println(" Least common multiple: " + a * b / c + "\n Maximum common divisor: " + c);
  }
}

Refer to previous posts on this site.


Related articles: