Binary maximum common divisor Algorithm

Source: Internet
Author: User

The Euclid Algorithm for Finding the maximum common divisor requires a large number of Modulo operations, which is a complex task on most computers, in contrast, the subtraction operation, the parity of the test number, and the execution speed of the half operation are faster.

The binary maximum common divisor algorithm avoids the remainder process of the Euclid algorithm.

The maximum divisor is based on the following facts:

  1. If both A and B are even numbers, gcd (a, B) = 2 * gcd (A/2, B/2)
  2. If a is an odd number and B is an even number, gcd (a, B) = gcd (A/2, B/2)
  3. If both A and B are odd, gcd (a, B) = gcd (a-B)/2, B)

Therefore, the algorithm for writing the maximum divisor of binary data is as follows (in C ):

[CPP]View plaincopy
  1. Int gcd (int A, int B ){
  2. Int c = 1;
  3. While (a-B ){
  4. If (A & 1 ){
  5. If (B & 1 ){
  6. If (A> B) A = (a-B)> 1; else B = (B-a)> 1;
  7. }
  8. Else B> = 1;
  9. }
  10. Else {
  11. If (B & 1) A >>= 1; else C <<= 1, A >>= 1, B >>= 1;
  12. }
  13. }
  14. Return C *;
  15. }

Or

[CPP]View plaincopy
    1. Int gcd (int u, int v ){
    2. Int K = 1, t;
    3. While (~ U & 1 &&~ V & 1) k <= 1, u> = 1, V> = 1;
    4. T = (U & 1 )? -V: U> 1;
    5. Do {
    6. While (~ T & 1) T> = 1;
    7. If (T> 0) u = T; else v =-T;
    8. } While (t = u-V );
    9. Return u * K;
    10. }

Binary maximum common divisor Algorithm

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.