Beg Greatest common divisor

Source: Internet
Author: User
Tags greatest common divisor

1. Time complexity of exhaustive algorithm (O (n))

//From small to large
Public Static intgcdintMintN) {intGCD =1; for(inti =2; I <= m && i <= N; i++) { if(m% i = =0&& n% i = =0) {GCD=i; } } returnGCD; }
From big to small
Public Static int gcd (intint N) {
int 1 ;          for (int1; i--) {            if00) {                = i;                  Break ;            }        }         return gcd;    }
//Exhaustive algorithm the divisor of number n is not likely to be larger than N/2
Public Static intgcdintMintN) {intGCD = 1; if(m% n = = 0) { returnN; } for(inti = N/2; I >= 1; i--) { if(m% i = = 0 && n% i = = 0) {GCD=i; Break; } } returnGCD; }

2. Recursive time complexity (O (LOGN))

 Public Static int gcd (intint  n) {        if (m% n = = 0)            {return c11> n;        }         Else {            return gcd (n, m% N);        }    }

3, while cycle time complexity (O (LOGN))

 Public Static int gcd (intint  n) {        int remainder = m% N;          while (Remainder > 0) {            = n;             = remainder;             = m% n;        }         return n;    }

Beg Greatest common divisor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.