为什么我的计算多个整数的最大公约数的代码什么也没有返回?

时间:2014-05-28 10:44:42

标签: java arrays greatest-common-divisor

我编写了以下代码来计算未指定数量的整数的gcd。

import java.util.Scanner;
public class GcdOfUnspecifiedNumberOfIntegers {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    int[] list = new int[5];

    for (int i = 0; i < 5; i++) {
        System.out.println("Enter a number: ");
        list[i] = input.nextInt();
    }

    gcd(list);
}

// Get the gcd of multiple integers
public static void gcd(int...numbers) {
    int gcd = 1;

    for (int i = 0; i < numbers.length; i++) {
        gcd = gcdOfTwo(gcd, numbers[i]);
    }

System.out.println("The gcd is: " + gcd);

}

// Get the gcd of two integers
public static int gcdOfTwo(int a, int b) {
    int gcdOfTwo = 1;
    int possibleGcd = 1;

    while (gcdOfTwo <= a && gcdOfTwo <= b) {
        if (a % possibleGcd == 0 && b % possibleGcd == 0) {
            gcdOfTwo = possibleGcd;
            possibleGcd++;
        }
    }

    return gcdOfTwo;
}

}

我的想法是得到两个数字的gcd(比如它的GCD),得到GCD的gcd和第三个数字,依此类推。

问题看起来像&#34; gcd(list)&#34;没有正常工作。输入所有整数后,按回车键,没有任何反应。

---更新---

我已经将ifGcd ++移出了if语句,但它仍然有问题,因为控制台给了我这个:

Enter a number: 
1
Enter a number: 
2
Enter a number: 
3
Enter a number: 
4
Enter a number: 
5
Exception in thread "main" java.lang.ArithmeticException: / by zero
at GcdOfUnspecifiedNumberOfIntegers.gcdOfTwo(GcdOfUnspecifiedNumberOfIntegers.java:35)
at GcdOfUnspecifiedNumberOfIntegers.gcd(GcdOfUnspecifiedNumberOfIntegers.java:22)
at GcdOfUnspecifiedNumberOfIntegers.main(GcdOfUnspecifiedNumberOfIntegers.java:14)

解决

我应该使用while(possibleGcd&lt; = a&amp;&amp; possibleGcd&lt; = b)而不是while(gcdOfTwo&lt; = a&amp;&amp; gcdOfTwo&lt; = b)。

3 个答案:

答案 0 :(得分:1)

将您的while循环更改为:

while (possibleGcd <= a && possibleGcd <= b) {
    if (a % possibleGcd == 0 && b % possibleGcd == 0) {
        gcdOfTwo = possibleGcd;
    }
    possibleGcd++;
}

答案 1 :(得分:0)

这个循环:

while (gcdOfTwo <= a && gcdOfTwo <= b) {
    if (a % possibleGcd == 0 && b % possibleGcd == 0) {
        gcdOfTwo = possibleGcd;
        possibleGcd++;
    }
}

无限运行,因为你没有增加gcdOfTw(如果gcdOfTwo = possibleGcd你不进去,possibleGcd++永远不会被执行)

答案 2 :(得分:0)

while (gcdOfTwo <= a && gcdOfTwo <= b) {
    if (a % possibleGcd != 0 || b % possibleGcd != 0) {
        break;
    }
    gcdOfTwo = possibleGcd;
    possibleGcd++;
}