计算GCD

时间:2013-12-27 18:27:33

标签: java methods greatest-common-divisor

我需要帮助才能获得两个输入数字的GCD。我不知道为什么它不会归还GCD。例如55和125的GCD将是5.任何帮助将不胜感激。它必须使用方法,而不是算法。

public static void main(String[] args)throws IOException {
        // TODO code application logic here
        //Intialize BufferReader
       minator);
        int gcd=GCD(numerator,denominator);
        System.out.println("GCD: "+gcd);


    }
     public static  int GCD(int numerator,int denominator){

       int remainder = numerator % denominator;

    if (remainder == 0)

        return denominator;

    else

        return GCD(denominator, remainder);

}

}

6 个答案:

答案 0 :(得分:1)

我尝试了你的代码,它因堆栈溢出异常而失败。您应该确保在问题中提供此类信息。

无论如何,这是Euclids GCD的更传统的实现:

public static int GCD(int numerator, int denominator)
{
    if (denominator == 0)
        return numerator;

    return GCD(denominator, numerator % denominator);
}

答案 1 :(得分:1)

尝试

public static int gcd(int m,int n){
       if(n==0)
         return m;
       else if(n>m)
         return gcd(n,m);
       else
        return gcd(n,m%n);
}

答案 2 :(得分:0)

public static  int GCD(int numerator,int denominator){
         if(numerator < denominator){
                 int numswap=denominator;
                 denominator=numerator;
                 numerator=numswap;
        }
         int remainder=numerator%denominator; 
         if (remainder == 0){
             return denominator;
         }
         System.out.println(numerator+" "+denominator);
         return GCD(denominator, remainder);

    }

使用if(numerator < denominator)代替if(numerator > denominator)

答案 3 :(得分:0)

获得两个数字a和b的gcd的最简单,最快速和最短的方法是这个递归函数:

int gcd(int a, int b) {
    if (b == 0)
        return a;
    else
        return gcd (b, a % b);
 }

答案 4 :(得分:0)

最大公约数(GCD)可以用减法计算,假设数字是正整数:

 public class GCD {
    public static void main(String[] args) {

        System.out.println(gcd(84,18)); //6
        System.out.println(gcd(30,60)); // 30
        System.out.println(gcd(125,55)); // 5

    }

    //only for positive integers 
    public static int gcd(int a, int b) {

        while (a != b) {

            if(a>b) {    
                a = a - b;    
            } else {    
                b = b - a;    
            }                      
        }
        return a;                
    }
}

答案 5 :(得分:0)

我认为一个简短而紧凑的gcd功能可以是:

public static long gcd (long a, long b) {
    if(a<b){
        a = (a^b)^(b = a);
    }
    while (b != 0) {
        a = ((a %= b)^b)^(b = a); //using the fact that xor is left associative
    }
    return a;
}