java算法:求兩個正整數的最大公約數和最小公倍數

題目:輸入兩個正整數 m 和 n,求其最大公約數和最小公倍數。
1.程序分析:利用輾除法。
最大公約數:
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);
}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章