Euclid is the most basic theorem in number theory, which is based on the expansion of Euclidean algorithm in solving the same residual equation, modulo inverse element and so on.
First of all, to introduce a few concepts, some basic concepts in number theory in fact in primary school, but for a long time and did not use them, so here again to take out a refresher.
We often use a|b to mean that B can divide a (b > A), that is, b/a is an integer, but the "|" It is easy to confuse with absolute values, geometric definitions, conditional probabilities during use, so here we use a\b to denote that a can divide B.
Approximate: If b\a, it is said that B is an approximate of a.
Multiples: If b\a, then A is a multiple of B.
Greatest common divisor: gcd (A, b) = Max{k | K\a and k\b}.
Least common multiple: LCM (A, b) = Min{k | k>0, a\k and B\k}
So now we are faced with an important question, give a series of numbers, we want to get these numbers by a program greatest common divisor or least common multiple, what should we do?
It is easy to think of the poor, and of course, the cost is to sacrifice a lot of time, we need to use better thinking to simplify the process.
Method for calculating greatest common divisor: Euclidean algorithm.
N>M,GCD (m,n) = gcd (n% m, m), gcd (0,n) = N.
Prove:
n = QM + r,r>0.
We assume that there is a D, which is the male factor of M and N, i.e. d\a and d\b.
You can see r = n-qm, if c = xa + YB, and d\a,d\b, then d\c. Here is the same reason, so d\r, plus before the d\b, the theorem is established.
Based on this conclusion, when we solve GCD (m,n) (n > M), we can turn to GCD (n m, m).
When seeking gcd (n m, m), you can turn to GCD (m% (n%m), n%m)
......
This has formed a recursive nature of the solution process, it may be said that the recursive process you will be questioned, the above proof process we give the same common factors, but how to ensure that it is the largest public factor (greatest common divisor) it? Imagine this recursive process, and if the last level of recursion is guaranteed to be the maximum common factor, then eventually we will return a greatest common divisor.
So now one of the main problems we're going to solve is: what's the bottom of recursion? Or, what level of recursion does it begin with? Imagine that the end of the recursion, gcd (A, a, b) must have a number is 0, and then we define in the theorem: gcd (a,0) = A.A is actually the entire recursive process of the solution, which ensures that the recursive process of passing the approximate is always greatest common divisor.
When designing a recursive program, in order to get the return value (that is, a in the previous paragraph), we specify the GCD (a, B) function a>b, so that the return result is: gcd (a,0), return a.
The reference code is as follows:
#include <cstdlib>#include<iostream>usingnamespace std; Long long gcd (intint b) { if0) return A; Else return gcd (b, a%b);}
Number theory and its application--Euclidean algorithm