我想让用户输入三个数字,然后让程序在使用递归的同时始终使用Euclid算法计算GCD。
我的代码现在实现了两个输入数字。我了解计算a和b的GCD并将其称为结果d的方法。然后使用第三个输入(c)和d查找GCD,并本质上再次重复Euclid算法;我不确定如何在代码中实现这一点。
import java.util.Scanner;
public class RecursionDemo {
public static void main (String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Enter first number: ");
int a = userInput.nextInt();
System.out.println("Enter second number: ");
int b = userInput.nextInt();
System.out.println("GCD is: " + gCd(a, b));
}
public static int gCd(int a, int b) {
if(b == 0){
return a;
}
return gCd(b, a%b);
}
}
真正让我失望的部分是使用递归来解决我的问题。
到目前为止,我知道我需要实现:
System.out.println("Enter third number: ");
int c = userInput.nextInt();
d = //Not sure here
//And then modify my recursion method to find GCD.
任何帮助或建议,将不胜感激!
d = gCd (a, b);
System.out.println("GCD is: " + gCd(d, c));
请注意,您可以gCd
使用任意两个参数(而不仅仅是a
和)来调用函数b
。为了更好地理解和减少混乱,您可能希望重命名其参数,如下所示:
public static int gCd(int x, int y) {
if(y == 0) {
return x;
}
return gCd(y, x%y);
}
因此,首先用x = a
和调用它,y = b
以找到a
和的GCD b
。将结果存储到新变量中d
。之后,您再次调用它,x = d
而GCD又是a
和b
,和y = c
。这样就得到了所有三个数字的GCD。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句