当前位置: 移动技术网 > IT编程>开发语言>Java > Java求两个正整数的最大公约数和最小公倍数

Java求两个正整数的最大公约数和最小公倍数

2019年07月22日  | 移动技术网IT编程  | 我要评论

刘志庚为什么怕太子辉,开讲啦 李健,落日风雷

题目:输入两个正整数m和n,求其最大公约数和最小公倍数。

程序分析:利用辗除法。

最大公约数:

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);
  }
}

最小公倍数和最大公约数:

import java.util.scanner;
public class candc
{
  //下面的方法是求出最大公约数
  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
  {
    //取得输入值
    //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("最小公倍数:" + a * b / c + "\n最大公约数:" + c);
  }
}

大家可以参考移动技术网以前发布的文章。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网