Home > Java > javaTutorial > body text

How to find the greatest common divisor in Java?

藏色散人
Release: 2019-05-22 15:38:13
Original
18483 people have browsed it

How to find the greatest common divisor in Java?

#How to find the greatest common divisor in Java?

Greatest Common Divisor

①Definition

The common divisors of several natural numbers are called these The common divisor of the numbers; the largest one is called the greatest common divisor of these numbers.

②Euclidean division

Also known as "Euclidean algorithm", it is an algorithm for finding the greatest common divisor

Find two numbers Greatest common divisor: If m > n, let remainder remaining = m%n, if the remainder is not 0, then let m = n, n = remainder, continue = m%n again, until remainder = 0, at which time n is Greatest common divisor.

Find the greatest common divisor of multiple numbers: first find the greatest common divisor of two of the numbers, then find the greatest common divisor of this greatest common divisor and the third number, and continue in turn until the last one So far, the final greatest common divisor obtained is the greatest common divisor of the required numbers

③Code implementation

public static int maxCommonDivisor(int m, int n) {  
        if (m < n) {     // 保证被除数大于除数
            int temp = m;  
            m = n;  
            n = temp;  
        }  
        while (m % n != 0) {  // 在余数不能为0时,进行循环  
            int temp = m % n;  
            m = n;  
            n = temp;  
        }  
        return n;    // 返回最大公约数  
    }
Copy after login

The above is the detailed content of How to find the greatest common divisor in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template