我需要了解这段代码的逻辑。我很难理解其背后的逻辑。请有人可以向我解释一下

时间:2019-07-23 23:22:57

标签: java

有人可以帮我理解GPD方法的概念

有人可以解释一下gcd方法背后的逻辑。

import java.util.Scanner;

 public class GreatestCommonDivisorMethod {

 public static void main(String[] args) {

 Scanner input = new Scanner(System.in);

 System.out.print("Enter first integer: ");
 int n1 = input.nextInt();
 System.out.print("Enter second integer: ");
 int n2 = input.nextInt();
 System.out.println("The greatest common divisor for " + n1 +
 " and " + n2 + " is " + gcd(n1, n2));
 }

 public static int gcd(int n1, int n2) {
 int gcd = 1; // Initial gcd is 1
 int k = 2; // Possible gcd

 while (k <= n1 && k <= n2) {
 if (n1 % k == 0 && n2 % k == 0)
 gcd = k; // Update gcd
 k++;
 }

 return gcd; // Return gcd
 }
}

我只需要帮助来了解此代码的逻辑

没有错误消息

0 个答案:

没有答案