JAVA数据结构与算法——求最大公约数!!

求a和b的最大公约数,求解过程如下:

假设a>b,设r1=mod(a,b),再设r2=mod(b,r1),r3=mod(r1,r2) ,一直计算下去,直到mod(rn-1,rn)=0,这时,rn就是a和b的最大公约数。

例:求91、52的最大公约数

1、mod(91,52)= 39  (注:取余数)

2、mod(52,39)=13

3、mod(39,13)=0,

即13位91、52的最大公约数。

代码演示如下:

public class Maxgy {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个参数的值:");
int a = sc.nextInt();
System.out.println("请输入第二个参数的值:");
int b = sc.nextInt();
int cmax = a > b ? a : b;
int cmin = a < b ? a : b;
int d = cmax % cmin;
while (d != 0) {
cmax = cmin;
cmin = d;
d = cmax % cmin;
}
System.out.println("最大公约数:" + cmin);
}
}

原文地址:https://www.cnblogs.com/qqzhulu/p/10073939.html