Elementary number theory-Euclidean algorithm

Source: Internet
Author: User

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

This algorithm is called Euclidean algorithm. will not overflow, because gcdThe number of recursive layers of a function does not exceed4.785lgN+ 1.6723ItsInN=max{a,b}。LetgcdThe highest number of recursive layers isgcdF n , F n -1). The GCD can also be used to find the least common multiple LCM (a, A, a, b) of two integers a and a. This conclusion can easily be obtained by the unique decomposition of the
theory. It is not difficult to verify GCD (A, B) *LCM (A, b) =a*b.

But don't be careless even with the formula. If you write the LCM as a *b/gcd (a, B), you may lose a lot of points--a*b may overflow! The correct notation is to first divide and then multiply, namely A/GCD (A, B). In this way, the function will not go wrong as long as the final result is guaranteed to be within the int range on the surface.
But this is not the case with the previous code: even if the final answer is within the int range, it is possible that the intermediate process is out of bounds. Notice the details of this
, after all, algorithmic contests are not mathematical contests.

Number theory preliminary-Euclidean 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.