程序分析:利用輾除法。
最大公約數:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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); } } |
最小公倍數和最大公約數:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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); } } |
大家可以參考服務器之家以前發布的文章。