要求最大公約數采用歐幾里德演算法(也叫做輾轉相除法),通過求出兩個數的最大公約數,就可求出兩數之間的最小公倍數,利用兩數的積再除他們的最大公約數,即得到最小公倍數,
(以下是代碼↓)
import java.util.Scanner;
public class GCD&LCM{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("請輸入兩個整數:");
int a = input.nextInt();
int b = input.nextInt();
int GCD = 0;
int temp = 0;
if(a < b) temp = b;
else temp = a;
for(int i = temp ; i > 0 ; i--){
GCD = i;
if(a % i == 0 && b % i == 0) break;
}
System.out.println("最大公約數為:"+GCD+"\t"+"最小公倍數為:"+(a*b)/GCD);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/41675.html
標籤:java
上一篇:cannot retrive initial cluster cluster partitions from initial uris
