![](/img/trans.png)
[英]Why is my Java program to merge 2 integer arrays only giving correct output to a certain point?
[英]Why is my program giving an incorrect output in certain cases?
我已经在Java中实现了欧几里德算法,以找到两个给定数字的最大公约数(GCD)。
在大多数情况下,我的程序运行正常,我已经用一些随机的数字集进行了测试,但是,我发现在一个案例中(我知道)它给出了一个不正确的输出,这是针对以下组合的数字:
输入整数a:8965输入整数b:55
该计划的输出应为55,但情况并非如此。 给出的结果如下:
gcd = 1执行时间:0.005747ms。
我不确定为什么这个特定的数字组合会导致问题,因为它适用于其他数字,例如,这是一组不同数字的结果:
输入整数a:15000
输入整数b:5325
gcd = 75
执行时间:0.007389ms。
import java.util.Scanner;
public class EuclideanAlgorithm {
public static void main (String [] args) {
int a, b;
try(Scanner sc = new Scanner(System.in);) {
System.out.print("Enter integer a: ");
a = sc.nextInt();
System.out.print("Enter integer b: ");
b = sc.nextInt();
}
long start = System.nanoTime();
int answer = EuclideanAlgorithm(a, b);
long stop = System.nanoTime();
System.out.println("gcd = " + answer);
System.out.println("Execution time: " + ((stop - start) / 1e+6) + "ms.");
}
public EuclideanAlgorithm() {}; //Suppress default constructor
private static int EuclideanAlgorithm(int a, int b) {
if ( (a == 0) || (b == 0)) {
return 0;
}
if (b > a) {
int temp = a;
a = b;
b = temp;
}
int gcd = 1;
while(gcd != 0) {
if( (a % b) == 0) {
break;
}
gcd = a % b;
a = b;
b = gcd;
}
return gcd;
}
}
每当你的a
数字a
, b
是另一个数字a
倍数时,那么你的if
条件将导致break
并且将返回1
,这是不正确的。 但算法的其余部分也是不正确的。
根据欧几里得算法的伪代码:
function gcd(a, b)
while b ≠ 0
t := b
b := a mod b
a := t
return a
你需要检查b
是不是0
,而不是gcd。 您需要修改代码以匹配此算法; 您的代码目前不符合此算法。
因为while while循环中的if条件
int gcd = 1;
while(gcd != 0) {
if( (a % b) == 0) {
break;
}
gcd = a % b;
a = b;
b = gcd;
}
因此,如果开头的%b = 0 - >结果总是等于1。
您需要单独处理该案例。
int gcd = b;
while(a % b != 0){
gcd = a % b;
a = b;
b = gcd;
}
很容易55分8965这意味着你在第一行打破程序并返回你的初始值1。
相反,像这样的东西可以帮助。
int gcd = 1;
if( (a % b) == 0) {
return b;
}
while(gcd != 0) {
if( (a % b) == 0) {
break;
}
gcd = a % b;
a = b;
b = gcd;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.