簡體   English   中英

實現歐幾里德最大公分母方法的無限循環

[英]Infinite loop in implementation of Euclid's greatest common denominator method

第二個println語句的邏輯錯誤導致我的代碼中出現無限循環。

它在while循環中,我理解導致它繼續打印,因為while測試是真的。 分別使用48和18作為num1和num2,我得到GCD的正確答案是6.打印輸出語句的位置是錯誤的,我無法弄清楚放在哪里。

只要兩個整數都不是負數,我的代碼就會找到兩個整數的GCD。 我使用了Euclid的方法。

謝謝你的幫助!

import java.util.*;

public class Chapter5Lab_Problem1 {


  public static void main(String[] args) { 
    Scanner console = new Scanner(System.in);
    System.out.print("Type the first integer to find GCD");
    int num1 = console.nextInt();
    System.out.print("Type the second integer to find GCD ");
    int num2 = console.nextInt();
    gcd(num1,num2);
  }

  public static void gcd( int x, int y){
    while( x >= 0 && y >= 0){
      if( x == 0){
        System.out.println("The GCD is " + y);
      }
      while( y != 0){
        if( x > y){
          x = x - y;
        }else{
          y = y - x;
        }

      }
     System.out.println("The GCF is " + x); 
    } 
  } 
}

X和Y將始終> = 0.它們在此算法中的最小值為0,因此第一個while語句的條件始終成立。 嘗試x > 0 && y > 0

這是一個遞歸的答案。 老師喜歡遞歸。 當程序保持無限或太長時,遞歸是有風險的。

public static int GCD(int n1, int n2){

  if(a==0 || b==0)
    return a+b;

  return GCD(n2, n1%n2)
}

如果你必須做一個循環,這是實現

int n3;
while(n != 0 || n2!= 0){

  n3 = n2;
  n2 = n1%n2;
  n1 = n3;
}

return n1+n2;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM