欧几里德算法:
Code
using System;
using System.Collections.Generic;
using System.Text;
namespace ojilide
{
class Program
{
static void Main(string[] args)
{
Console.Write("最大公约数为{0}",gcd(10,5));
Console.WriteLine();
Console.Write("最小公倍数为{0}", gbs(2, 3));
Console.WriteLine();
}
//欧几里德算法又称辗转相除法,用于计算两个整数a,b的最大公约数。
//其计算原理依赖于下面的定理: 定理:gcd(a,b) = gcd(b,a mod b)
//其算法用C#语言描述为
/**//// <summary>
/// 最大公约数
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static int gcd(int a, int b)
{
if (a == 0)
{
return b;
}
if (b == 0)
{
return a;
}
if (a < b)
{
int temp;
temp = b;
b = a;
a = temp;
}
while (b != 0)
{
int temp;
temp = a % b;
a = b;
b = temp;
}
return a;
}
/**//// <summary>
/// 附:最小公倍数
/// </summary>
/// <param name="m"></param>
/// <param name="n"></param>
/// <returns></returns>
public static int gbs(int m, int n)
{
return m * n / gcd(m, n);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ojilide
{
class Program
{
static void Main(string[] args)
{
Console.Write("最大公约数为{0}",gcd(10,5));
Console.WriteLine();
Console.Write("最小公倍数为{0}", gbs(2, 3));
Console.WriteLine();
}
//欧几里德算法又称辗转相除法,用于计算两个整数a,b的最大公约数。
//其计算原理依赖于下面的定理: 定理:gcd(a,b) = gcd(b,a mod b)
//其算法用C#语言描述为
/**//// <summary>
/// 最大公约数
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static int gcd(int a, int b)
{
if (a == 0)
{
return b;
}
if (b == 0)
{
return a;
}
if (a < b)
{
int temp;
temp = b;
b = a;
a = temp;
}
while (b != 0)
{
int temp;
temp = a % b;
a = b;
b = temp;
}
return a;
}
/**//// <summary>
/// 附:最小公倍数
/// </summary>
/// <param name="m"></param>
/// <param name="n"></param>
/// <returns></returns>
public static int gbs(int m, int n)
{
return m * n / gcd(m, n);
}
}
}