Find the greatest common divisor of two numbers based on Java

1. Euclidean division method

To find the greatest common divisor of two numbers using Java , you can use the Euclidean algorithm (Euclidean algorithm) to solve it.

2. Example

The following is an example code for finding the greatest common divisor of two numbers using Java :

public class GCD {
   // 求最大公约数的方法
   public static int findGCD(int a, int b) {
       // 辗转相除法
       while (b != 0) {
           int temp = a % b;
           a = b;
           b = temp;
       }
       return a;
   }
   public static void main(String[] args) {
       int num1 = 36;
       int num2 = 48;
       int gcd = findGCD(num1, num2);
       System.out.println("最大公约数为:" + gcd);
   }
}

In this example, we define a method named findGCD () to find the greatest common divisor, using the idea of ​​euclidean division. In the main() method, we define two numbers num1 and num2 , and then call the findGCD () method to calculate their greatest common divisor and save the result in the gcd variable. Finally, use the System.out.println () method to output the results to the console. You can replace num1 and num2 in the code with the two numbers you need to find the greatest common divisor, and then run the code to get the result of the greatest common divisor.

If you do not have a Java running environment, you can use an online Java editor .

Online java editor - https://c.runoob.com/compile/10/

Enter the program on the left, click Run, and output the results on the right.

Guess you like

Origin blog.csdn.net/weixin_45770896/article/details/132918559