欧几里德算法:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif) Code
using System;
using System.Collections.Generic;
using System.Text;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
namespace ojilide
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif) ![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif) {
class Program
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif) {
static void Main(string[] args)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif) {
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#语言描述为
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//// <summary>
/// 最大公约数
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static int gcd(int a, int b)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif) {
if (a == 0)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif) {
return b;
}
if (b == 0)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif) {
return a;
}
if (a < b)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif) {
int temp;
temp = b;
b = a;
a = temp;
}
while (b != 0)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif) {
int temp;
temp = a % b;
a = b;
b = temp;
}
return a;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif) /**//// <summary>
/// 附:最小公倍数
/// </summary>
/// <param name="m"></param>
/// <param name="n"></param>
/// <returns></returns>
public static int gbs(int m, int n)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif) {
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
return m * n / gcd(m, n);
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
|