C gets an example of the greatest common divisor and least common multiple of two Numbers

  • 2020-05-30 20:58:00
  • OfStack

Greatest common divisor: the largest constraint that two or more integers have in common.

Least common multiple: if there is a natural number a that is divisible by the natural number b, a is said to be a multiple of b, b is a divisor of a, and for two integers, the smallest multiple of the two Numbers in common.


/// <summary>
///  The greatest common divisor 
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static int GCD(int a, int b)
{
int gcd = 1;
int min = a > b ? b : a;
for (int i = min; i >= 1; i--)
{
if (a % i == 0 && b % i == 0)
{
gcd = i;
break;
}
}
return gcd;
}
/// <summary>
///  Least common multiple 
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static int LCM(int a, int b)
{
int lcm = a * b;
int max = a > b ? a : b;
for (int i = max, len = a * b; i <= len; i++)
{
if (i % a == 0 && i % b == 0)
{
lcm = i;
break;
}
}
return lcm;
}


Related articles: