求两个数的最大公约数,我们可用辗转相除法
在数学上,辗转相除法是一种求解最大公约数的方法。它的算法步骤如下:
a、 b相除;
向 a分配 b;
向 b分配剩余;
如果 b是0, a是最大的,否则,步骤1-3直到 b是0为止。
代码如下:
public class Text01 {
public static void main(String[] args) {
demo(4,44);//应用下列方法
}
static void demo(int a,int b){
int c ;//为a,b两个数的模
int d;//用于下面两个数的交换
if(a>b){
c = a%b;
if(c==0){
System.out.println("该组数的最大公约数为"+b);
}else {
while(true){
a = b;
b = c;
c = a%b;//辗转相除法
if(c==0){
break;
}
}
System.out.println("该数组的最大公约数为"+b);
}
} else {
d = a;
a = b;
b = d;//交换a,b两个值
c = a%b;
if(c==0){
System.out.println("该组数的最大公约数为"+b);
}else {
while(true){
a = b;
b = c;
c = a%b;//再辗转相除法
if(c==0){
break;
}
}
System.out.println("该数组的最大公约数为"+b);
}
}
}
}
这样代码会有重复的逻辑,所以我们想想可不可以将重复的代码再封装一下,答案是可以的,我们将重复代码再进行封装后
/**
* 输入两个整数求最大公约数
*/
public class Text {
public static void main(String[] args) {
demo(4,44);
}
static void demo(int a,int b){
int c ;//为a,b两个数的模
int d;//用于下面两个数的交换
if(a>b){
sum(a,b);//导入下面的方法
}else {
d = a;
a = b;
b = d;//交换两个值
sum(a,b);
}
}
public static void sum(int a,int b){
int c;
c = a%b;
if(c==0){
System.out.println("该组数的最大公约数为"+b);
}else {
while(true){
a = b;
b = c;
c = a%b;
if(c==0){
break;
}
}
System.out.println("该数组的最大公约数为"+b);
}
}
}
这样代码就好看多了。