To divide and seek greatest common divisor

Source: Internet
Author: User
Tags greatest common divisor

Order

The most commonly used algorithm for greatest common divisor is Euclid's algorithm, also known as the Euclidean method. The problem is defined as the greatest common divisor gcd (i,j) for I and J, where I and j are integers and may be set to i>j.
The algorithm can be expressed recursively:
1. If j can divide I, then gcd (i,j) =j;

2. J cannot divide the I, make r=i%j, then gcd (i,j) =GCD (j,r).

C implementation
int gcd (intint  j) {    int r = i% j;     return 0 ? J:GCD (J, R);}
Analysis

Step 1 of the algorithm, apparently established (greatest common divisor definition);

To prove step 2:

Set D is the greatest common divisor of I and J,
So I=md,j=nd,m and n coprime (otherwise D is not greatest common divisor).
I=kj+r,k=⌊m/n⌋,k≥1 can be obtained by R=I%J (we have previously assumed i>j).
Put the i=md,j=nd in the Get
Md=knd+r
So
R= (M-KN) d
M-kn and M are also coprime.
So get D is the greatest common divisor of J and R.

Time Complexity Analysis:
The inverse of the algorithm, the final remainder is 0, the second-to-last remainder is D, the third time to the penultimate is kd,k>1 ...
Because of the formation of a sequence, {0,d,kd,nkd+d,...}
The n term of the series plus the n+1 term is smaller than the n+2 term, so it is faster than the Fibonacci sequence.
We know that the Fibonacci sequence growth rate is exponential, and the number of columns to be analyzed is exponential.
The Euclidean algorithm needs k times, then J=o (2^k), then K=o (LG J).

So Euclidean algorithm greatest common divisor time complexity is the order of magnitude, the speed is very fast.

To divide and seek 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.