原题如下:
Let’s consider all integers 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≤a<b≤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.
Input
The first line contains a single integer t (1≤t≤100) — the number of test cases. The description of the test cases follows.
The only line of each test case contains a single integer n (2≤n≤10^6).
Output
For each test case, output the maximum value of gcd(a,b) among all 1≤a<b≤n.
Example
input |
---|
2 3 5 |
output |
1 2 |
Note
In the first test case, gcd(1,2)=gcd(2,3)=gcd(1,3)=1.
In the second test case, 2 is the maximum possible value, corresponding to gcd(2,4).
翻译如下:
让我们考虑从1到n(包括)范围内的所有整数。
在这个范围内的所有不同整数对中,找出整数对的最大可能最大公约数。形式上,gcd(a,b)的最大值,其中1≤a<b≤n。
两个正整数a和b的最大公约数gcd(a,b)是a和b的最大公约数。
输入
第一行为单个整数t(1≤t≤100)——测试用例个数。下面是测试用例的描述。
每个测试用例只有一行包含单个整数n(2≤n≤10^6)。
输出
对于每个测试用例,输出所有1≤a<b≤n中gcd(a,b)的最大值。
第一次思路:
#include<stdio.h>
int gcd(int n);
int main()
{
int trr[110];
int t,i,j,n,maxnumber;
scanf("%d",&t);
for(i=1;i<=t;i++)
{
scanf("%d",&n);
maxnumber=gcd(n);
for(j=n-1;j>maxnumber;j--) //不断修改寻找的下界,防止超时
{
if(gcd(j)>maxnumber)
maxnumber=gcd(j);
}
trr[i]=maxnumber;
}
for(i=1;i<=t;i++)
printf("%d\n",trr[i]);
return 0;
}
int gcd(int n) //寻找最大因数
{
int i;
for(i=n-1;i>=1;i--)
{
if(n%i==0)
return i;
}
return 1;
}
思路是,要想找到一组小于n的两个数的最大公因数,也就是找到一个数非本身的最大因数,比如:
当n=5时,5的最大非本身因数是1,4的最大非本身因数是2,3的最大非本身因数也是1,因此找到答案是2.
但是却会报超时。
那么换个思路,从1开始想,往上增加,就会发现递增规律是乘以2,所以把n除以2即可得到答案。(奇数则自动去除小数部分)
代码如下:
#include<stdio.h>
int main()
{
int t,i,n;
scanf("%d",&t);
for(i=1;i<=t;i++)
{
scanf("%d",&n);
printf("%d\n",n/2);
}
return 0;
}