#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;
};
C++ 求最大公约数四种方法getGreatestCommonDivisor
最新推荐文章于 2024-03-12 14:19:34 发布