Java求兩個正整數的最大公約數和最小公倍數。本站提示廣大學習愛好者:(Java求兩個正整數的最大公約數和最小公倍數)文章只能為提供參考,不一定能成為您想要的結果。以下是Java求兩個正整數的最大公約數和最小公倍數正文
題目:輸入兩個正整數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);
}
}
大家可以參考以前發布的文章。