-
-
Save techlarry/c6ccf9c06b55f8777983dafcaff14654 to your computer and use it in GitHub Desktop.
`Greatest Common Divisor` (最大公约数) GCD(m, n) is: if m modulo n equals 0 then n; else GCD(n, m mod n);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<cstdlib> | |
using namespace std; | |
int gcd(int a, int b) | |
{ | |
// swap a and b | |
if (a<b) | |
{ | |
a = a^b; b = a^b; a = a^b; | |
} | |
if (a%b==0) | |
return b; | |
else | |
return gcd(b, (a%b)); | |
} | |
int main() | |
{ | |
srand(6); | |
int a, b; | |
for (int i=0; i<10; ++i) | |
{ | |
a = rand(), b= rand(); | |
cout << " The greastest common divisor of " << a | |
<< " and " << b << " is " << gcd(a, b) | |
<< endl; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
求最大公约数算法: | |
**辗转相除法** | |
有两整数a和b: | |
1. a%b得余数c | |
2. 若c=0,则b即为两数的最大公约数 | |
3. 若c≠0,则a=b,b=c,再回去执行① | |
例如求27和15的最大公约数过程为: | |
1. 27÷15 余12 | |
2. 15÷12余3 | |
3. 12÷3余0 | |
因此,3即为最大公约数 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment