[英]Problems creating greatest common divisor in java
我遵循此計算的邏輯,但這似乎只會給我帶來無盡的循環。 我可以幫忙嗎?
我應該使用的邏輯是:
查找兩個正整數x和y的最大公約數的公式遵循歐幾里得算法,如下:1.反復從y中減去x直到y <x。 2.交換x和y的值。 3.重復步驟1和2,直到x =0。4. y是兩個數字的最大公約數。
這是我的代碼:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package project4.pkg3;
/**
*
* @author LMFS
*/
import java.util.Scanner;
public class Project43 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int numOne, numTwo;
String c = "";
Scanner sc = new Scanner(System.in);
String another = "y";
while (another.equalsIgnoreCase("y")) {
System.out.println("Enter first number: ");
numOne = sc.nextInt();
System.out.println("Enter second number: ");
numTwo = sc.nextInt();
c = doMath(numOne, numTwo);
//use static method here.
System.out.println("Greatest common divisor: " + c);
System.out.println();
System.out.println("Continue? (y/n): ");
another = sc.next();
}
}
public static String doMath(int numOne, int numTwo) {
while (numOne != 0) {
System.out.println("//debugging line 48: " + numOne);
while (numTwo > numOne) {
numTwo -= numOne;
System.out.println("//debugging line 52: " + numTwo);
}
while (numOne > numTwo) {
numOne -= numTwo;
System.out.println("//debugging line 57: " + numOne);
}
}
return Integer.toString(numTwo);
}
}
編輯:這解決了。 我將靜態方法更改為:
public static int egcd(int a, int b) {
if (a == 0)
return b;
while (b != 0) {
if (a > b)
a = a - b;
else
b = b - a;
}
return a;
}
使用算法的實現方式, numOne
或numTwo
可能首先達到零。 但是,如果numTwo
到達零之前numOne
的話,那么你的里面第二個嵌套循環doMath
永遠不會退出,因為條件將永遠是正確的。
解決此問題的一種方法是添加
if (numTwo == 0) {
return numOne;
}
在兩個嵌套循環之間。
另外,我建議從此方法的返回中刪除Integer.toString
部分,並讓它返回一個int
或Integer
而不是String
。
提示:我一直認為,當數字彼此相等時,歐幾里得算法會中斷。 找到的號碼是GCD。
另外,我認為您在主計算循環中不需要多個循環。 嘗試將它們替換為if
語句。 因此,更容易發現錯誤(嘗試使用數字1和1運行程序)
在方法doMath
此修復:
// Until one of the numbers divides by other
while (numOne % numTwo != 0 && numTwo % numOne != 0) {
代替:
while (numOne != 0) {
在退貨之前進行此更改
int result = numOne / numTwo == 0 ? numOne : numTwo;
return Integer.toString(result);
在控制台上,我得到以下結果:
Enter first number:
14
Enter second number:
49
... some debugging log
Greatest common divisor: 7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.