我需要帮助来获取两个输入数字的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);

}

}

最佳答案

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)

08-03 16:51