题目描述:
Let’s consider all in the range from 1 to n(inclusive).
Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a ,b), where 1
≤
\leq
≤ a
≤
\leq
≤ b
≤
\leq
≤n.
The greatest common divisor, gcd(a, b), of two positive integers a and b is the biggest integer that is a divisor of both a and b.
输入描述:
The first line contains a single integer t (1
≤
\leq
≤ t
≤
\leq
≤ 100) - the number of test cases. The description of the test cases follows.The only one line of each test case contains a single integer (2
≤
\leq
≤ n
≤
\leq
≤ 106) .
输出描述:
For each test case, output the maximum value of gcd(a, b) among all 1
≤
\leq
≤ a
≤
\leq
≤ b
≤
\leq
≤ n.
首先给出最终的AC通过结果代码:
#include <iostream>
using namespace std;
int main(){
int NumOfInput; //输入的个数
cin >> NumOfInput;
while(NumOfInput--){
int MaxNum;
cin >> MaxNum; //n的最大值
if(MaxNum % 2 == 0)
cout << MaxNum / 2 << endl;
else
cout << (MaxNum-1) /2 << endl;
}
return 0;
}
分析:
- 题目看起来比较复杂,总结为一句话“求最大公约数的最大值”。 最常用的求两个数的最大公约数的求法为辗转相除法,其实现代码如下:
int GreaComDiv(int a, int b){
int c = b;
while(a%b != 0){
c = a % b;
a = b;
b = c;
}
return c;
}
- 求是最大公约数的最大值,即转为求2与n或者n-1的最大公约数,理解了这个之后接下来就简单啦,直接往上套就可以了!
总结:
- 求最大公约数的最大值,可以把问题转化为为求最小值和最大值的最大公约数。