Java 欧几里得实现中的无限循环&x27;s最大公分母法
第二个Java 欧几里得实现中的无限循环&x27;s最大公分母法,java,algorithm,greatest-common-divisor,Java,Algorithm,Greatest Common Divisor,第二个println语句的逻辑错误导致下面的代码中出现无限循环 它在while循环中,我知道它会一直打印,因为while测试是真的。分别使用48和18作为num1和num2,我得到了GCD为6的正确答案。打印出来的语句的位置是错误的,我不知道该放在哪里 我的代码找到两个整数的GCD,只要其中一个不是负的。我用了欧几里得的方法 谢谢你的帮助 import java.util.*; public class Chapter5Lab_Problem1 { public static void
println
语句的逻辑错误导致下面的代码中出现无限循环
它在while循环中,我知道它会一直打印,因为while测试是真的。分别使用48和18作为num1和num2,我得到了GCD为6的正确答案。打印出来的语句的位置是错误的,我不知道该放在哪里
我的代码找到两个整数的GCD,只要其中一个不是负的。我用了欧几里得的方法
谢谢你的帮助
import java.util.*;
public class Chapter5Lab_Problem1 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Type the first integer to find GCD");
int num1 = console.nextInt();
System.out.print("Type the second integer to find GCD ");
int num2 = console.nextInt();
gcd(num1,num2);
}
public static void gcd( int x, int y){
while( x >= 0 && y >= 0){
if( x == 0){
System.out.println("The GCD is " + y);
}
while( y != 0){
if( x > y){
x = x - y;
}else{
y = y - x;
}
}
System.out.println("The GCF is " + x);
}
}
}
X和Y始终大于等于0。在这个算法中,它们可以变成的最小值是0,因此第一个while语句的条件始终成立。请尝试
x>0&&y>0
。这是一个递归的答案。老师喜欢递归。当递归是无限的或堆栈太长,程序无法容纳时,递归是有风险的
public static int GCD(int n1, int n2){
if(a==0 || b==0)
return a+b;
return GCD(n2, n1%n2)
}
如果您必须执行循环,那么下面是该实现
int n3;
while(n != 0 || n2!= 0){
n3 = n2;
n2 = n1%n2;
n1 = n3;
}
return n1+n2;
你为什么要连续减法而不是取模。我不知道如何正确使用它。你能告诉我你将如何使用模来改变方法吗?谢谢!嘘,事情总是这么简单。为了找到SOP声明的存放位置,我简直快疯了。完全忽略了这一点。非常感谢,先生!