2

我想要求用户输入三个数字,然后让程序在使用递归的同时使用欧几里得算法计算 GCD。

我的代码现在实现了两个输入数字。我了解计算a和b的GCD的方法,并将其称为结果d。然后使用第三个输入 (c) 和 d 找到 GCD 并基本上再次重复欧几里得算法;我不确定如何在代码中实现这一点。

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.

任何帮助或建议将不胜感激!

4

2 回答 2

2
d = gCd (a, b);
System.out.println("GCD is: " + gCd(d, c));

请注意,您可以gCd使用任何两个参数调用您的函数,而不仅仅是aand b。为了更好地理解和减少混淆,您可能需要重命名其参数,如下所示:

 public static int gCd(int x, int y) {
     if(y == 0) {
         return x;
     }
     return gCd(y, x%y);
 }

所以,首先你用x = aand调用它y = b来找到aand的 GCD b。将结果存储到新变量d中。之后,您再次调用它x = d,依次是aandb和的 GCD y = c。这样你就得到了所有三个数字的 GCD。

于 2014-03-22T22:40:44.533 回答
1

可以迭代 gcd 方法以获得更大数字集的 gcd。例如:

gCd(a, b, c) = gCd( gCd(a, b), c)

gCd(a, b, c, d) = gCd( gCd(a, b, c), d)那么那么
gCd(a, b, c, d) = gCd( gCd( gCd(a, b), c), d)

简单,具体的解决方案:

System.out.println("GCD is: " + gCd( gCd(a, b), c) );

但是,如果您注意到,递归正在进行。我创建了一个将整数数组作为输入的方法。它适用于大小为 3 或任何大小的数组。以下是方法:

/* returns gcd of two numbers: a and b */
public static int gCd(int a, int b) {
    if (b == 0) {
        return a;
    }
    return gCd(b, a%b);
}

/* returns gcf of an array of numbers */
public static int gCd(int[] numbers)
{
    int result = numbers[0]; // first number

    for(int i = 1; i < numbers.length; i++) {
        result = gCd(result, numbers[i]); // gcf of itself and next #
    }
    return result;
}

因此,要将其与您的代码相关联:

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("Enter third number: ");
int c = userInput.nextInt();

// you can do this
System.out.println("GCD is: " + gCd( gCd(a, b), c) );

// or you can do this
int[] numbers = {a, b, c};
int d = gCd(numbers);

System.out.println("GCD is: " + d);

样本输入/输出:

Enter first number: 
12
Enter second number: 
18
Enter third number: 
30
GCD is: 6
GCD is: 6
于 2014-03-22T22:55:47.607 回答