Number Theory preliminary-Euclidean algorithm, number theory-Euclidean Algorithm

Source: Internet
Author: User

Number Theory preliminary-Euclidean algorithm, number theory-Euclidean Algorithm

1 int judge (int * X) {2 X [2]/= gcd (X [2], X [1]); 3 for (int I = 3; I <= k; I ++) X [2]/= gcd (X [I], X [2]); 4 return X [2] = 1; 5}

This algorithm is called Euclidean algorithm. Does not overflow, because The number of recursive layers of The gcd function cannot exceed 4.785lg.N+ 1.6723, of whichN= Max {A,B}. Gcd (FN,FN-1 ). Gcd can also be used to obtain the least common multiples lcm (a, B) of two integers a and B ). This conclusion is easily determined by the unique decomposition.
. Therefore, it is not difficult to verify that gcd (a, B) * lcm (a, B) = a * B.

However, do not take things into account even if you have a formula. If you write lcm as a * B/gcd (a, B), you may lose a lot of scores-a * B may overflow! The correct method is to divide the cursor first, that is, a/gcd (a, B) * B. In this way, as long as the question surface ensures that the final result is within the int range, this function will not go wrong.
However, the previous Code does not: even if the final answer is within the int range, the intermediate process may cross the border. Note that
After all, algorithm competitions are not mathematical competitions.

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.