2.7 Greatest common divisor problems
Question: Ask for a greatest common divisor of two numbers.
For the problem: the first thing to look at is to find a minimum value in the two number N m. It then iterates from this value to 1. Once n%i==0&&m%i==0 then I is this greatest common divisor. The principle is self-evident. The code is not attached.
Then one is the more classical Euclidean algorithm. In essence, this is the principle. GCD (N,m) represents the greatest common divisor of N and M.
1:GCD (n,m) = GCD (n%m,m) (n>m)
2:GCD (0,a) = A This is legal. Because 0 can be counted as a divisor (nonsense, but again for the sake of rigor).
Formula 1 is a recursive relationship. Formula 2 is the end of judgment. Exactly the definition of a recursive relationship. (I wonder if Kunth can find a closed form of this.) )
First explain the principle:
For 1: Make r=n%m proof gcd (n,m) = GCD (r,m). where n = km+r (k belongs to a positive integer, because n>m so k!=0). Then R = n-km.
That is to say: gcd (n,m) = GCD (n-km,m). That is to prove that the largest common factor of n-km and M is the largest common factor of N and M
Based on the prime number expression. N-KM have a common factor of N and M only. It is easy to know that the largest common factor of n-km and M is the largest male factor of N and M. Evidence.
2nd the charm of numbers--skills in numbers