【蓝桥云课】最大公约数与最小公倍数

一、最大公约数gcd(a,b)

引例:

a=24,其因子有1、2、3、4、6、8、12、24
b=15,其因子有1、3、5、15
最大公约数gcd(a,b)=gcd(24,15)=3

欧几里得辗转算法:

a = max(a,b);
b = min(a,b);
while(b>0){
	t = a%b;
	a = b;
	b = t;
}

运算过程:

a = 24, b = 15
1) t = 24%15 = 9,a = 15,b = 9;
2) t = 15%9 = 6, a = 9, b = 6;
3) t= 9%6 =3, a = 6, b = 3;
4) t = 6%3 = 0, a = 3, b = 0;
b>0条件不满足,while循环停止。

【蓝桥云课】最大公约数与最小公倍数_第1张图片

程序代码:

import java.util.Scanner;
public class Test{
	public static void main(String[] args){
		int a = 0, b = 0;
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
			a = sc.nextInt();
			b = sc.nextInt();
			System.out.println("欧几里得" + gcd_1(a,b));
			System.out.println("递归" + gcd_2(a,b));
		}
	}
	public static int gcd_1(int a, int b){
		while(b>0){
			int t = a%b;
			a = b;
			b = t;//gcd(a,b)=>gcd(b,a%b);
		}
		return a;
	}
	public static int gcd_2(int a, int b){
		return b==0?a:gcd_2(b, a%b);
	}
}

二、最小公倍数lcm(a,b)

L C M ( a , b ) = a ∗ b g c d ( a , b ) LCM(a,b)=\frac{a*b}{gcd(a,b)} LCM(a,b)=gcd(a,b)ab

你可能感兴趣的:(蓝桥杯,蓝桥杯,java)