1. 定義法
package GCD;
import java.util.Scanner;
//定義法状共,根據(jù)最大公約數(shù)的定義進(jìn)行求解
public class Definition {
public static void main(String[] args) {
System.out.println("請輸入兩個(gè)非零整數(shù):");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("這兩個(gè)整數(shù)的最大公約數(shù)為:"+ definition(a,b));;
}
public static int definition(int num1, int num2) {
int res;
if (num1 > num2)
res = num2;
else
res = num1;
while(true) {
if (num1%res == 0 && num2%res == 0)
break;
else
res = res - 1;
}
return res;
}
}
2. 歐幾里得算法
package GCD;
import java.util.Scanner;
//歐幾里得算法,又稱輾轉(zhuǎn)相除法
public class Euclid {
public static void main(String[] args) {
System.out.println("請輸入兩個(gè)非零整數(shù):");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("這兩個(gè)整數(shù)的最大公約數(shù)為:"+ euclid(a,b));;
}
public static int euclid(int inte1, int inte2) {
int surplus ;
surplus = inte1%inte2;
while(surplus != 0) {
inte1 = inte2;
inte2 = surplus ;
surplus = inte1%inte2;
}
return inte2;
}
}
3. 輾轉(zhuǎn)相減法
package GCD;
import java.util.Scanner;
//輾轉(zhuǎn)相減法
public class Subtraction {
public static void main(String[] args) {
System.out.println("請輸入兩個(gè)非零整數(shù):");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("這兩個(gè)整數(shù)的最大公約數(shù)為:"+subtraction(a,b));;
}
public static int subtraction (int num1, int num2) {
while(true) {
if (num1 > num2)
num1 -= num2;
else if (num1 < num2)
num2 -= num1;
else
return num1;
}
}
}
4. 分解質(zhì)因子法
package GCD;
import java.util.ArrayList;
import java.util.Scanner;
//質(zhì)因數(shù)分解法构灸,將兩個(gè)數(shù)的所有質(zhì)因子分解出來,然后將公共的因子相乘岸梨,得到的就是最大公約數(shù)喜颁。
public class Prime {
public static void main(String[] args) {
System.out.println("請輸入兩個(gè)非零整數(shù):");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("這兩個(gè)整數(shù)的最大公約數(shù)為:"+ getGCD(a,b));
}
public static ArrayList<Integer> getPrimeFactors(int num) {
// 初始化質(zhì)因子序列
ArrayList<Integer> factorList = new ArrayList();
// 循環(huán)迭代求質(zhì)因子
int i = 2;
while (i <= num) {
if (num % i == 0) {
factorList.add(i);
num /= i;
} else {
i++;
}
}
return factorList;
}
public static int getGCD(int num1, int num2) {
// 先獲得絕對值稠氮,保證負(fù)數(shù)也可以求
num1 = Math.abs(num1);
num2 = Math.abs(num2);
// 獲得兩個(gè)數(shù)的質(zhì)因子序列
ArrayList<Integer> factors1 = getPrimeFactors(num1);
ArrayList<Integer> factors2 = getPrimeFactors(num2);
// 設(shè)初始最大公約數(shù)為 1
int gcd = 1;
// 返回從開頭找公共的質(zhì)因子,相乘起來
for (int i = 0; i < factors1.size(); i++) {
for (int j = 0; j < factors2.size(); j++) {
if (factors1.get(i) == factors2.get(j)) {
// 將公共的質(zhì)因子累乘
gcd *= factors1.get(i);
// num2 的質(zhì)因子序列除去找到的半开,減少第二次重復(fù)找
factors2.remove(j);
// 退出第二重循環(huán), 一次只找一對公共的質(zhì)因子
j = factors2.size();
}
}
}
return gcd;
}
}
初學(xué)者一枚隔披,如有問題歡迎指正~