C++ 求最大公约数四种方法getGreatestCommonDivisor

#include <iostream>
using namespace std;
void grc1(int a, int b);
void grc2(int a, int b);
void grc3(int a, int b);
void grc4(int a, int b);
int main() {
	int m, n, i;
	cout << "Please type two numbers to get their greatest common divisor:" << endl;
	cin >> m >> n;
	cout << "Plesae type a number in 1, 2, 3, 4 to choose which way the program will run" << endl;
	cout << "1 : 辗转相除法(欧几里得算法)" << endl;
	cout << "2 : 更向减损法" << endl;
	cout << "3 : 更向减损法与位移算法的结合优化" << endl;
	cout << "4 : 暴力枚举法" << endl;
	cout << "Your choice will be:" << endl;
	cin >> i;
	if (i == 1)
		grc1(m, n);//辗转相除法
	if (i == 2)
		grc2(m, n);//更相减损法
	if (i == 3)
		grc3(m, n);//Stein算法
	if (i == 4)
		grc4(m, n);//暴力枚举法

};
void grc1(int a, int b) {
	int big = a > b ? a : b;
	int small = a < b ? a : b;
	int temp = big % small;
	cout << big << " mod " << small << " = " << big % small << endl;
	while (temp != 0) {
		big = small;
		small = temp;
		temp = big % small;
		cout << big << " mod " << small << " = " << big % small << endl;
	};
	cout << small;
};
void grc2(int a, int b) {
	int big = a > b ? a : b;
	int small = a < b ? a : b;
	int temp = big - small;
	cout << big << " - " << small << " = " << temp << endl;
	while (temp != 0) {
		big = a > b ? a : b;
		small = a < b ? a : b;
		temp = big - small;
		cout << big << " - " << small << " = " << big - small << endl;
		a = temp;
		b = small;
	};
	cout << small;
};
void grc3(int a, int b) {
	int big = a > b ? a : b;
	int small = a < b ? a : b;
	int temp = big - small;
	while (temp != 0) {
		big = a > b ? a : b;
		small = a < b ? a : b;
		temp = big - small;
		while (big % 2 == 0) {
			cout << big << " / 2 = " << big / 2 << endl;
			big = big / 2;
		}
		while (small % 2 == 0) {
			cout << small << " / 2 = " << small / 2 << endl;
			small = small / 2;
		}
		cout << big << " - " << small << " = " << big - small << endl;
		a = temp;
		b = small;
	};
	cout << small;
};
void grc4(int a, int b) {
	int big = a > b ? a : b;
	int small = a < b ? a : b;
	int temp = small;
	for (temp = small;temp >= 1;temp--) {
		if (big % temp == 0 && small % temp == 0) {
			break;
		}
	}
	cout << temp;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值