可用“辗转相除法”求,算法如下:
1)求出m除以n的余数,存放在变量r中;
2)若余数r为0则执行步骤6,否则执行步骤3;
3)把除数作为新的被除数,把余数作为新的除数;
4)求出新的余数r;
5)重复步骤2到4;
6)输出n,n即为最大公约数。
/// <summary>
/// 求最大公约数
/// 辗转相除法
/// </summary>
/// <param name="num1"></param>
/// <param name="num2"></param>
/// <returns></returns>
public static int getGreatestCommonMeasure(int num1, int num2)
{
if (num1 == 0) return Math.Abs(num2);
if (num2 == 0) return Math.Abs(num1);
int num3 = 0;
//insure: num1 >= num2
if (num1 < num2)
{
num3 = num1;
num1 = num2;
num2 = num3;
}
num3 = num1 % num2;
while (num3 != 0)
{
num1 = num2;
num2 = num3;
num3 = num1 % num2;
}
return Math.Abs(num2);
}
/// <summary>
/// 求最小公倍数
/// </summary>
/// <param name="num1"></param>
/// <param name="num2"></param>
/// <returns></returns>
public static int getLeastCommonMultiple(int num1, int num2)
{
int GCM = getGreatestCommonMeasure(num1,num2);
if (GCM == 0) return 0;
return num1 * num2 / GCM;
}
/// 求最大公约数
/// 辗转相除法
/// </summary>
/// <param name="num1"></param>
/// <param name="num2"></param>
/// <returns></returns>
public static int getGreatestCommonMeasure(int num1, int num2)
{
if (num1 == 0) return Math.Abs(num2);
if (num2 == 0) return Math.Abs(num1);
int num3 = 0;
//insure: num1 >= num2
if (num1 < num2)
{
num3 = num1;
num1 = num2;
num2 = num3;
}
num3 = num1 % num2;
while (num3 != 0)
{
num1 = num2;
num2 = num3;
num3 = num1 % num2;
}
return Math.Abs(num2);
}
/// <summary>
/// 求最小公倍数
/// </summary>
/// <param name="num1"></param>
/// <param name="num2"></param>
/// <returns></returns>
public static int getLeastCommonMultiple(int num1, int num2)
{
int GCM = getGreatestCommonMeasure(num1,num2);
if (GCM == 0) return 0;
return num1 * num2 / GCM;
}