Java最大公因數程式
在Java中,可以使用java.lang.Math
類別中的gcd
方法來計算兩個整數的最大公因數(Greatest Common Divisor, GCD)。這個方法返回兩個整數的乘積除以它們的差得到的結果。以下是一個簡單的例子:
import java.lang.Math;
public class GCDExample {
public static void main(String[] args) {
int a = 48;
int b = 36;
int gcd = Math.gcd(a, b);
System.out.println("The GCD of " + a + " and " + b + " is " + gcd);
}
}
在上面的程式碼中,我們定義了兩個整數a
和b
,並使用Math.gcd
方法來計算它們的最大公因數,然後將結果印出。
如果你想要自己實現最大公因數算法,可以使用埃拉托斯特尼質數篩法(Eratosthenes's sieve)或者更簡單的輾轉相除法( Euclidean algorithm )。以下是一個使用輾轉相除法實現最大公因數算法的例子:
public class GCDExample {
public static void main(String[] args) {
int a = 48;
int b = 36;
int gcd = gcd(a, b);
System.out.println("The GCD of " + a + " and " + b + " is " + gcd);
}
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
在上面的程式碼中,gcd
方法使用輾轉相除法來計算兩個整數的最大公因數。這個算法的基本思想是:兩個整數的最大公因數等於較小的數除以它們的差得到的結果。
注意:Math.gcd
方法在Java 1.8及以上版本中是可用的,如果你的Java版本較低,可能需要自己實現最大公因數算法。