如何用JAVA程序实现GCD

来源:百度知道 编辑:UC知道 时间:2024/05/03 07:34:42

public static int gcd(int m,int n){
if (m<n){
int t = n;
n = m;
m = t;
}
int r;
do{
r = m % n;
m = n;
n = r;
}while (r != 0);
return m;

public class T {
public static void main(String[] args) {
System.out.println(gcd(16,24));
}

static int gcd(int x, int y){
if(x==0)return y;
if(y==0)return x;
if(x>y)return gcd(x%y, y);
else return gcd(x, y%x);
}
}

public static int gcd(int x,int y){
if(x<0||y<0)
System.exit(1);
int temp;
while(y>0){
temp=x%y;
x=y;
y=temp
}
return x;
}