最大公约数与最小公倍数的C语言实现

#include
#include

int Divisor(int a, int b)  //最大公约数
{
	if ((a <= 0) || (b <= 0))
		return -1;

	int min;
	min = (a <= b) ? a : b;

	while (min)
	{
		if ((a%min == 0) && (b%min == 0))
			return min;
		else
			min--;
	}
	return -1;
}

int Multiple(int a, int b)   //最小公倍数
{
	if ((a <= 0) || (b <= 0))
		return -1;

	int max;
	max = (a >= b) ? a : b;

	while (max)
	{
		if ((max%a == 0) && (max%b == 0))
			return max;
		else
			max++;
	}
	return -1;
}
int main()
{
	int a = 8;
	int b = 12;

	int ret_D = Divisor(a, b);
	if (ret_D != -1)
		printf("greatest common divisor=%d\n", ret_D);
	else
		printf("no greatest common divisor\n");

	int ret_M = Multiple(a, b);
	if (ret_D != -1)
		printf("least common multiple=%d\n", ret_M);
	else
		printf("no least common multiple\n");

	system("pause");
	return 0;
}

你可能感兴趣的:(C)