最大公因数GCD和最小公倍数LCM
给定两个整数,求出这两个整数的最大公约数和最小公倍数
本文中,假定这两个整数是m和n,且m>=n>=0。
求最大公约数GCD的几种算法
一、Consecutive Integer Test——连续整数检测算法
由最大公约数的概念,我们可以知道,能够同时被两个给定整数整除的最大整数,即是最大公约数。那么我们可以最简单的想出用暴力搜索的方法,从两个整数中较小的那一个开始,向下穷举遍历,找到最大公约数。当然,这种方法是低效的,存在着很大的不确定性。
- Step1:将min{m,n}的值赋给t。
- Step2:判断t是否为0,如果是0,返回max{m,n};否则,进入第三步。
- Step3:m除以t,如果余数为0,则进入第四步;否则进入第五步。
-
Step4:n除以t,如果余数为0,则返回t值作为结果;否则进入第五步。
-
Step5:把t的值减1,返回第三步。
int ConsecutiveIntegerTest(int m, int n) { int t = n; while (t != 0) { if (m % t == 0) { if (n % t == 0) return t; else --t; } else --t; } return m;//最终的返回值m,即为m和n的最大公约数。 }
二、Euclidean(recursion)——欧几里得算法
求取最大公约数最经典的算法莫过于欧几里得算法了,既是所谓的辗转相除法,比起暴利搜索更加高效稳定。
欧几里得算法有递归和非递归两种表达方式。
(递归方式)
int Euclidean_Recursion(int m, int n) {
if (n == 0)
return m;
return Euclidean_Recursion(n, m % n);
}
(非递归方式)
int Euclidean_nonRecursion(int m, int n) {
while (n != 0) {
int r = m % n;
m = n;
n = r;
}
return m;
}
求最小公倍数LCM
LCM = m * n / GCD
附上代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-- >0) {
int A = sc.nextInt();
int B = sc.nextInt();
gcd(A,B);
System.out.println(lcm(A,B));
}
}
private static int lcm(int m,int n) {
int LCM = m*n/gcd(m,n);
return LCM; //return m*n/gcd(m,n);
}
private static int gcd(int m, int n) {
if (n==0)
return m;
else return gcd(n,m%n);
}
}