CodeForces-1370A.Maximum GCD

原题如下:

A.Maximum GCD
time limit per test: 1 second
memory limit per test: 256 megabytes
input: standard input
output: standard output

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;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值