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