牛客-max

链接:https://www.nowcoder.com/acm/contest/143/G
来源:牛客网
 

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

Give two positive integer c, n. You need to find a pair of integer (a,b) satisfy 1<=a,b<=n and the greatest common division of a and b is c.And you need to maximize the product of a and b

输入描述:

The first line has two positive integer c,n

输出描述:

Output the maximum product of a and b.

If there are no such a and b, just output -1

示例1

输入

2 4

输出

8

说明

a=2,b=4

备注:

1<=c,n<=10^9

题解:题目要求找出n范围内以c为最大公约数的两个数字,在n内最大以c为因子的数b=n/c*c;

又因为两个相邻的数字乘以一个数后最大公约数一定是那个数,例如,2*c和3*c或者5*c和6*c,所以另一个数a=b-c;

最后注意特例,当b==c时,a=c,当n<c时输出-1;

#include <bits/stdc++.h>
using namespace std;
#define ll long long

int main()
{
ll c,n;
cin>>c>>n;
ll a,b;

b=n/c*c;
if(b!=c)
a=b-c;
else
a=c;

if(c<n)
cout<<a*b<<endl;
else if(c==n)
    cout<<c*c<<endl;
else
     cout<<"-1"<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/WN_795/article/details/81381329