代码:
穷举法
//穷举法
public static Int32 GetMaxCommonDivisorWithExhaustion(Int32 biggerNum, Int32 smallerNum)
{
Int32 maxDivisor = 0;
for (int index = 1; index < smallerNum / 2; index++)
{
if (biggerNum % index == 0 && smallerNum % index == 0)
{
maxDivisor = index;
}
}
return maxDivisor;
}
更相减损法
//更相减损法(递归)
public static Int32 GetMaxCommonDivisorWithGxjsRecursionRecursion(Int32 biggerNum, Int32 smallerNum)
{
return biggerNum != smallerNum ? (smallerNum > (biggerNum - smallerNum) ? GetMaxCommonDivisorWithGxjsRecursionRecursion(smallerNum, biggerNum - smallerNum) : GetMaxCommonDivisorWithGxjsRecursionRecursion(biggerNum - smallerNum, smallerNum)) : biggerNum;
}
//更相减损法(非递归)
public static Int32 GetMaxCommonDivisorWithGxjsRecursionNorecursion(Int32 biggerNum, Int32 smallerNum)
{
while (biggerNum != smallerNum)
{
if (smallerNum > biggerNum - smallerNum)
{
int temp = smallerNum;
smallerNum = biggerNum - smallerNum;
biggerNum = temp;
}
else
{
biggerNum -= smallerNum;
}
}
return biggerNum;
}
辗转相除法
//辗转相处法 (递归)
public static Int32 GetMaxCommonDivisorWithGcdRecursion(Int32 biggerNum, Int32 smallerNum)
{
return biggerNum % smallerNum == 0 ? smallerNum : GetMaxCommonDivisorWithGcdRecursion(smallerNum, biggerNum % smallerNum);
}
//辗转相处法 (非递归)
public static Int32 GetMaxCommonDivisorWithGcdNorecursion(Int32 biggerNum, Int32 smallerNum)
{
while (biggerNum % smallerNum != 0)
{
int temp = biggerNum;
biggerNum = smallerNum;
smallerNum = temp % smallerNum;
}
return smallerNum;
}
测试代码:
Stopwatch sw = new Stopwatch();
sw.Reset();
sw.Start();
{
for (int i = 0; i < 100000000; i++)
{
GetMaxCommonDivisorWithGxjsRecursionRecursion(260, 60);
}
}
sw.Stop();
Console.WriteLine("更相减损法(递归):" + sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
{
for (int i = 0; i < 100000000; i++)
{
GetMaxCommonDivisorWithGxjsRecursionNorecursion(260, 60);
}
}
sw.Stop();
Console.WriteLine("更相减损法(非递归):" + sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
{
for (int i = 0; i < 100000000; i++)
{
GetMaxCommonDivisorWithGcdRecursion(260, 60);
}
}
sw.Stop();
Console.WriteLine("辗转相除法:" + sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
{
for (int i = 0; i < 100000000; i++)
{
GetMaxCommonDivisorWithGcdNorecursion(260, 60);
}
}
sw.Stop();
Console.WriteLine("辗转相除法:(非递归)" + sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
{
for (int i = 0; i < 100000000; i++)
{
GetMaxCommonDivisorWithExhaustion(260, 60);
}
}
sw.Stop();
Console.WriteLine("穷举法:" + sw.ElapsedMilliseconds);
测试结果:
结论:
更相减损法>辗转相除法>穷举法
非递归普遍比递归表现的更好
更相减损法仍旧有改进的余地,辗转相除法的优势是除了之后余数不会比除数更大,更像减损法减了之后仍旧需要比较。
和我这种写法或许也有关系,进去的值已经判断了大小了,如果换成无序的传进去参数,或许会不一样。