输入两个正整数m和n,求其最大公约数和最小公倍数.用JAVA编写
要求按以下算法编写循环,每次用较大数作被除数,除以较小的数,若余数不为0进入下一轮循环,前一轮除数作新一轮的被除数,前一轮的余数作为新一轮除数,如此循环直到余数为0,最后...
要求按以下算法编写循环,每次用较大数作被除数,除以较小的数,若余数不为0进入下一轮循环,前一轮除数作新一轮的被除数,前一轮的余数作为新一轮除数,如此循环直到余数为0,最后的除数即为最大公约数,最小公倍数为两数之积除以最大公约数。
展开
2个回答
展开全部
public class Calc {
public static int getGCD(int x, int y) {
int max = 0;
int min = 0;
if (x > y) {
max = x;
min = y;
} else {
max = y;
min = x;
}
if (max % min == 0) {
return min;
} else {
return getGCD(min, max % min);
}
}
public static void getLCMAndGCD(int x, int y) {
int gcd = getGCD(x,y);
System.out.println("最大公约数:"+gcd);
System.out.println("最小公倍数:"+x*y/gcd);
}
public static void main(String[] args) {
getLCMAndGCD(18, 8);
}
}
展开全部
public static void main(String[] args) {
int num1 = 13;
int num2 = 3;
System.out.println("Max Convention is : "+ getMaxConvention(num1,num2));
System.out.println("LCM is :" + getLCM(num1,num2));
}
private static int getLCM(int num1,int num2){
if(num1 != num2){
return (num1 * num2)/getMaxConvention(num1,num2);
}
return num1;
}
private static int getMaxConvention(int num1,int num2){
if(num1 != num2){
int maxNum = num1 > num2 ? num1 : num2;
int minNum = num1 < num2 ? num1 : num2;
int mod = maxNum % minNum;
while((minNum % mod != 0) || (maxNum % mod != 0)){
maxNum = minNum;
minNum = mod;
mod = maxNum % minNum;
}
return mod;
}
return num1;
}
int num1 = 13;
int num2 = 3;
System.out.println("Max Convention is : "+ getMaxConvention(num1,num2));
System.out.println("LCM is :" + getLCM(num1,num2));
}
private static int getLCM(int num1,int num2){
if(num1 != num2){
return (num1 * num2)/getMaxConvention(num1,num2);
}
return num1;
}
private static int getMaxConvention(int num1,int num2){
if(num1 != num2){
int maxNum = num1 > num2 ? num1 : num2;
int minNum = num1 < num2 ? num1 : num2;
int mod = maxNum % minNum;
while((minNum % mod != 0) || (maxNum % mod != 0)){
maxNum = minNum;
minNum = mod;
mod = maxNum % minNum;
}
return mod;
}
return num1;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询