CF1152C Neko does Maths

题目传送门

CF1152C Neko does Maths

题目描述

Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.

Neko has two integers a and b . His goal is to find a non-negative integer k such that the least common multiple of a+k and b+k is the smallest possible. If there are multiple optimal integers kk, he needs to choose the smallest one.

Given his mathematical talent, Neko had no trouble getting Wrong Answer on this problem. Can you help him solve it?

翻译:

给定两个正整数a,b,找到非负整数k使a+k与b+k的最小公倍数最小,如有多解输出最小的k

输入格式

The only line contains two integers a and b ( 1≤a,b≤1e9 ).

输出格式

Print the smallest non-negative integer k( k≥0 ) such that the lowest common multiple of a+k and b+k is the smallest possible.

If there are many possible integers k giving the same value of the least common multiple, print the smallest one.

样例

输入样例1

6 10

输出样例1

2

输入样例2

21 31

输出样例2

9

输入样例3

5 10

输出样例3

0

说明与提示

In the first test, one should choose k=2 , as the least common multiple of 6+2 and 10+2 is 24 , which is the smallest least common multiple possible.


暴力解法就是枚举判断是否满足条件,这肯定是会超时的。

正解

因为公式

lcm(x,y)=\frac{x \times y}{gcd(x,y)}

所以

lcm(a+k,b+k)=\frac{(a+k)\times (b+k)}{gcd(a+k,b+k)}

因为

gcd(x,y)=gcd(x,y-x) 

其中 y > x

所以

gcd(a+k,b+k)=gcd(a+k,b+k-a-k)=gcd(a+k,b-a)

因此,我们可以枚举(b-a)的因子x,并将x假设为gcd(a+k , b-a)

因为要求最小化    \frac{(a+k)\times (b+k)}{gcd(a+k,b-a)}

所以(a+k) (b+k)应当尽可能的小,即k尽可能小

所以我们现在可以枚举x,并找到满足(a+k)%x==0 这个式子的最小k值(因为x必须是a+k的因子)

这个k值也可以用O(1)算出来

即        k=\left \lfloor \frac{a}{x} \right \rfloor\times x+x-a

其中 \left \lfloor \right \rfloor 表示向下取整

再用k算出lcm(a+k,b+k)

并求出最小的lcm值和k值即可

代码如下代码很丑

#include<bits/stdc++.h>
using namespace std;
long long a,b;
long long lcm=1e15-1,x,k=999999999999,y;
int main()
{
	scanf("%lld%lld",&a,&b);
	if(a>b) swap(a,b);
	for(int i=1;i<=sqrt(1.0*(b-a));i++)
	{
		if((b-a)%i!=0) continue;
		x=((a/i)+1)*i-a;
		y=(a+x)*(b+x)/i;
		if(y<lcm)
		{
			lcm=y;
			k=x;
		}
		else if(y==lcm&&x<k)
		k=x;
		x=((a/((b-a)/i)+1))*((b-a)/i)-a; //别忘了因子是成对出现的
		y=(a+x)*(b+x)/((b-a)/i);
		if(y<lcm)
		{
			lcm=y;
			k=x;
		}
		else if(y==lcm&&x<k)
		k=x;
	}
	cout<<k;
	return 0;
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值