1. 程式人生 > 實用技巧 >求n個最小公倍數

求n個最小公倍數

題目
如果兩個數很大,怎樣求最大公約數,最小公倍數?
如果是n個數呢?比如1000個數的最小公倍數

輸入
2 4 6
3 2 5 7

輸出
12
70

思路
首先最大公約數可以用輾轉相除法,定義為lcm(m,n),然後再定義一個方法gcd(m,n)求最大公約數,用公式法 :最小公倍數 = m * n / lcm(m,n),使用一個數組nums來裝輸入的資料,大小n由輸入決定int nums[] = new int[n];,然後在使用一個while迴圈,來輸入裝進陣列nums的資料。最後定義一個int a,儲存gcd(m,n)引數中的m。

不知道輾轉相除法,可以看我的這篇部落格,詳細介紹了的,很簡單。

程式碼
public class Test4 {
public static void main(String[] args) {
int i = 0,m;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//輸入要輸的個數
int nums[] = new int[n];
while (n != 0 ){
m = sc.nextInt();
if (m == 0){

        }else{
            nums[i] = m;
            i++;
        }
        n--;
    }
    int a =nums[0];//lcm的第一個引數

// System.out.println(Arrays.toString(nums));
for (int j = 1 ; j < nums.length; j++){
a = gcd(a,nums[j]);
}
System.out.println("他們的最小公倍數="+a);
}
//求最大公因數
public static int lcm(int m,int n ){
int left = (m > n)? m : n; //左邊是較大的數
int right = (m > n)? n : m; //右邊是較小的數
if ((left % right) == 0){
return right;
}
return lcm(right , left % right);
}
//求最小公倍數
public static int gcd(int m,int n){
return m * n /lcm(m , n);
}

}