天天看點

藍橋杯 java 算法訓練 5-1最小公倍數

算法訓練 5-1最小公倍數

資源限制

時間限制:1.0s 記憶體限制:256.0MB

問題描述

  編寫一函數lcm,求兩個正整數的最小公倍數。

樣例輸入

一個滿足題目要求的輸入範例。

例:

3 5

樣例輸出

與上面的樣例輸入對應的輸出。

import java.util.Scanner;
 
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int b = sc.nextInt();
		sc.close();
		System.out.println(lcm(a, b));
	}
	
	private static int lcm(int a, int b) {
		int g = gcd(a, b);
		return a * b / g;
	}
	
	private static int gcd(int a, int b) {
		if (b == 0) {
			return a;
		} else {
			return gcd(b, a % b);
		}
	}
}