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.