Skip to content

Instantly share code, notes, and snippets.

@techlarry
Created October 30, 2017 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techlarry/c6ccf9c06b55f8777983dafcaff14654 to your computer and use it in GitHub Desktop.
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);
#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;
}
}
求最大公约数算法:
**辗转相除法**
有两整数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