最伟大的公共除法器程序仅打印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;
}
} 
while (num1 <= k && k <= num2) 
{
if (num1 % k == 0 && num2 % k == 0)
gcd = k;
k++;  
}

看起来您在while循环中意外切换了num1k

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

将返回值分配给变量,然后打印

int answer = gcd(num1, num2);

然后在打印强制转换为字符串或使用toString方法时。

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

最新更新