![](/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.