题目:用辗转相除法,求两个整数的最大公约数,提示需先判断两个数的大小
#include <iostream>
using namespace std;
int main()
{
int a, b, t;
cout << "Enter two positive integers: ";
cin >> a >> b;
// Swap a and b if necessary so that a <= b
if (a > b) {
t = a;
a = b;
b = t;
}
// Use the Euclidean algorithm to find the GCD of a and b
while (a != 0) {
t = a;
a = b % a;
b = t;
}
cout << "The GCD is " << b << endl;
return 0;
}
首先从标准输入中读取两个正整数a和b,然后在使用辗转相除法之前检查a和b的大小。如果a比b大,则交换它们的值。
接下来,程序使用辗转相除法找到a和b的最大公约数。在每次循环中,该算法计算b除以a的余数,并将其赋值给b,将原来的b赋值给a,直到a为0。此时,变量b中存储的值就是a和b的最大公约数。
最后,程序输出最大公约数b的值并返回0作为结束代码。