两个正正数的最大公约数用程序算法来求解是算法里面比较入门的东西,这是我昨天试着写的,还望指正。
/*Author:Bruce
* Time:2009-4-7pm
* Function:obtain the biggest common divisor of two integer
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace BiggestCommonDivisor
{
class Program
{
/// <summary>
///obtain the biggest common divisor of two integer
/// </summary>
/// <param name="a">first integer</param>
/// <param name="b">second integer</param>
/// <returns></returns>
public static int CommonDivisor(int a, int b)
{
int div = 1;
try
{
for (int i = 2; i <= a && i <= b; i++)
{
while (a % i == 0 && b % i == 0)
{
div = div * i;
a = a / i;
b = b / i;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return div;
}
static void Main(string[] args)
{
int a, b;
Console.WriteLine("Please enter the first integer:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the second integer:");
b = Convert.ToInt32(Console.ReadLine());
int consuquence = CommonDivisor(a, b);
Console.WriteLine("The result is {0} ", consuquence);
Console.ReadLine();
}
}
}
* Time:2009-4-7pm
* Function:obtain the biggest common divisor of two integer
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace BiggestCommonDivisor
{
class Program
{
/// <summary>
///obtain the biggest common divisor of two integer
/// </summary>
/// <param name="a">first integer</param>
/// <param name="b">second integer</param>
/// <returns></returns>
public static int CommonDivisor(int a, int b)
{
int div = 1;
try
{
for (int i = 2; i <= a && i <= b; i++)
{
while (a % i == 0 && b % i == 0)
{
div = div * i;
a = a / i;
b = b / i;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return div;
}
static void Main(string[] args)
{
int a, b;
Console.WriteLine("Please enter the first integer:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the second integer:");
b = Convert.ToInt32(Console.ReadLine());
int consuquence = CommonDivisor(a, b);
Console.WriteLine("The result is {0} ", consuquence);
Console.ReadLine();
}
}
}