Mathematical principle:
There are two numbers of NUM1 and num2, assuming that the NUM1 is relatively large. Make remainder r = num1% num2.
When r = = 0 o'clock, that is, NUM1 can be divisible by num2, obviously num2 is the gcd of these two numbers.
When r!= 0 o'clock, make NUM1 = num2 (divisor is divisor), num2 = R (remainder divisor), do r = num1% num2. Recursion until r = = 0.
the above mathematical principles can be done with a specific two-digit analysis, so easy to understand.
Code implementation (Seek GCD):
Copy Code code as follows:
#include <iostream>
using namespace Std;
int gcd (int a, int b);/Declaration GCD function
Int main ()
{
int num1 = 1;
int num2 = 1;
cin >> num1 >> num2;
while (num1 = 0 | | num2 = = 0)/Determine if there are 0 value inputs, and then re-enter
{
cout << "input error!" << Endl;
cin >> num1 >> num2;
}
cout << "The GCD of" << num1 << "and" << num2 << "is:" << GCD (NUM1, num2) << endl;//invoke GCD function
return 0;
int gcd (int a, int b)//function definition
{
int max = a > B? A:B;
int min = a < b? A:B;
A = max;
b = min;
int r = a% B;
if (0 = r)//If a can be divisible by B, then B is gcd.
return b;
Else
return gcd (b, r);//recursion
}
The LCM of the method is based on the method of seeking gcd. Because LCM equals two number of product divided by GCD.
Code implementation (seek LCM):
Copy Code code as follows:
#include <iostream>
using namespace Std;
int gcd (int a, int b);/Declaration GCD function
Int main ()
{
int num1 = 1;
int num2 = 1;
int LCM = 1;
cin >> NUM1 >> num2;
while (num1 = 0 | | num2 = = 0)/Determine whether there are 0 value inputs, if any, reenter
{
& nbsp; cout << "input error!" << Endl;
cin >> num1 >> num2;
}
LCM = NUM1/GCD (NUM1, num2) * num2;//to a certain extent to prevent large numbers
cout << "the LCM "<< num1 <<" and "<< num2 <<" is: "<< LCM << Endl;
return 0;
}
int gcd (int a, int b)//function definition
{
int max = a > B? A:B;
int min = a < b? A:B;
A = max;
b = min;
int r = a% B;
if (0 = r)//If a can be divisible by B, then B is gcd.
return b;
Else
return gcd (b, r);//recursion
}
The above is only limit and seek two books of GCD and LCM, when the number has a lot, the law is still applicable, still need to be verified.