題目:輸入兩個正整數m和n,求其最大公約數和最小公倍數。
程序分析:利用輾除法。
在循環中,只要除數不等於0,用較大數除以較小的數,將小的一個數作為下一輪循環的大數,取得的余數作為下一輪循環的較小的數,如此循環直到較小的數的值為0,返回較大的數,此數即為最小公約數,最小公倍數為兩數之積除以最小公倍數。
1 package com.li.FiftyAlgorthm; 2 3 import java.util.Scanner; 4 5 /**b 6 * 題目:輸入兩個正整數m和n,求其最大公約數和最小公倍數。 程序分析:利用輾除法。 7 * 在循環中,只要除數不等於0,用較大數除以較小的數,將小的一個數作為下一輪循環的大數,取得的余數作為下一輪循環的較小的數,如此循環直到較小的數的值為0,返回 8 * 較大的數,此數即為最小公約數,最小公倍數為兩數之積除以最小公倍數。 9 * 10 * @author yejin 11 * 12 */ 13 public class CommonDiviser { 14 public static void main(String[] args) { 15 int a, b; 16 Scanner s1 = new Scanner(System.in); 17 Scanner s2 = new Scanner(System.in); 18 a = s1.nextInt(); 19 b = s2.nextInt(); 20 CommonDiviser cd = new CommonDiviser(); 21 int m = cd.division(a, b); 22 int n = a * b / m; 23 System.out.println("最大公約數: " + m); 24 System.out.println("最小公倍數: " + n); 25 } 26 27 public int division(int x, int y) { 28 int t; 29 if (x < y) { 30 t = x; 31 x = y; 32 y = t; 33 } 34 35 while (y != 0) { 36 if (x == y) 37 return 1; 38 else { 39 int k = x % y; 40 x = y; 41 y = k; 42 } 43 } 44 return x; 45 } 46 }