本文實例講述了java求最大公約數與最小公倍數的方法。分享給大家供大家參考,具體如下:
Gongyueshu.java文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
package math; public class Gongyueshu { public static void main(String[] args) { //從控制臺輸入兩個數據 int m = Integer.parseInt(args[ 0 ]); int n = Integer.parseInt(args[ 1 ]); int y = 1 ; int b = 1 ; System.out.println( "服務器之家測試結果:" ); if (m > 0 && n > 0 ) { //先判定這兩個數是否為倍數關系,如果是則小數為最大公約數,大數為最小公倍數 if (m % n == 0 || n % m == 0 ) { if (m >= n) { System.out.println( "最大公約數為" + n); System.out.println( "最小公倍數為" + m); } else { System.out.println( "最大公約數為" + m); System.out.println( "最小公倍數為" + n); } } //從2開始循環尋找兩數共同的因子,每找到一個即乘以公約數變量y與公倍數變量b //并把原來的兩個數除以共同的因子, //并把i置為1(continue出來要執行for的結束語句i++,所以下一次循環i依然從2開始)下一次循環 else { for ( int i = 2 ; i <= m ; i ++ ) { if (m % i == 0 && n % i == 0 ) { y *= i; b *= i; m /= i; n /= i; i = 1 ; continue ; } else if (m == i && (m % i != 0 || n % i != 0 )) { b = b * m * n; System.out.println( "最大公約數為" + y); System.out.println( "最小公倍數為" + b); } } } } else { System.out.println( "輸入錯誤" ); } } } |
此處需要由控制臺輸入參數,eclipse環境運行的設置步驟為Run》Run Configurations進入運行的調試配置界面,右側選項卡里有個(x)= Arguments選項(中文版本為(x)= 自變量),在此處設置運行時輸入的變量,如下圖所示:
運行結果:
希望本文所述對大家java程序設計有所幫助。
原文鏈接:https://www.oschina.net/code/snippet_2881024_58776