求最大公约数和分数约分问题

求A和B的最大公约数;化简A/B为最简分式

C++

#include <iostream>

using namespace std;

class Solution
{
public:
	int gcd(int a, int b)
	{
		int max, min, temp;
		a > b ? (max = a, min = b) : (min = a, max = b);
		while (min != 0)
		{
			temp = max % min;
			max = min;
			min = temp;
		}
		return max;
	}
	void simplification_fraction(int a, int b)
	{
		int greatest_common_divisor = this->gcd(a, b);
		cout << a / greatest_common_divisor << "/" << b / greatest_common_divisor << endl;

		// 求最简假分式
		// int max, min;
		// a > b ? (max = a, min = b) : (min = a, max = b);
		// if (greatest_common_divisor == 1)
		//     cout << max << "/" << min << endl;
		// else
		//     cout << max / greatest_common_divisor << "/" << min / greatest_common_divisor << endl;
	}
};

int main()
{
	int a, b;
	cin >> a >> b; // 输出两个数,求最大公约数和求最简分式

	Solution *s = new Solution();
	int greatest_common_divisor = s->gcd(a, b);
	cout << greatest_common_divisor << endl;
	s->simplification_fraction(a, b);
	delete s;
	system("pause");
	return 0;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部