最大公约数程序仅打印 1

Greatest Common Divisor Program Only Printing 1

我正在编写一个程序,您可以在其中输入两个整数,程序会找到这两个数字之间的最大公约数。

它运行良好,除了它打印“1”作为 GCD,即使这两个数字应该有不同的 GCD。 (示例:4 & 64。GCD 应该是 4,但仍然打印 1。)我无法弄清楚我的代码有什么问题。

对于那些想用一种方法回答的人,我做不到:这是一项要求我在同一个程序中使用两种不同方法的作业。请帮忙?

感谢阅读,祝你度过愉快的一周。

这是我的代码:

import java.util.Scanner;

public class greatestCommonDivisorMethod {

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        //Number entry prompts       
        System.out.print("Please enter first integer: ");
        int num1 = input.nextInt();
        System.out.print("Please enter second integer: ");
        int num2 = input.nextInt();

        //Result printed
        System.out.println("The greatest common divisor of " +num1+ " and " +num2+ " is " +gcd(num1, num2)+".");
    }


    public static int gcd(int num1, int num2) {
        int gcd = 1;
        int k = 2;
        while (num1 <= k && k <= num2) 
        {
             if (num1 % k == 0 && num2 % k == 0)
                 gcd = k;
                 k++;  
        }

        return gcd;
    }
} 

将你的return分配给一个变量然后打印它

int answer = gcd(num1, num2);

然后在打印时转换为 String 或使用 toString 方法。

 System.out.println("The greatest common divisor of " +answer.toString());

while 条件应该有 k<=num1 而不是 num1<=k

while (num1 <= k && k <= num2) 
{
      if (num1 % k == 0 && num2 % k == 0)
      gcd = k;
      k++;  
}

您似乎不小心在 while 循环中切换了 num1k