Codeforces Round #554 (Div. 2) C. 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 aa and bb. His goal is to find a non-negative integer kk such that the least common multiple of a+ka+k and b+kb+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?
The only line contains two integers aa and bb (1≤a,b≤1091≤a,b≤109).
Print the smallest non-negative integer kk (k≥0k≥0) such that the lowest common multiple of a+ka+k and b+kb+k is the smallest possible.
If there are many possible integers kk giving the same value of the least common multiple, print the smallest one.
6 10
2
21 31
9
5 10
0
In the first test, one should choose k=2k=2, as the least common multiple of 6+26+2 and 10+210+2 is 2424, which is the smallest least common multiple possible.
首先有个结论 gcd(a,b)=gcd(a,b-a), 因为假设gcd(a,b)=c,那么a%c=b%c=0,又有(a-b)%c=0,所以 gcd(a,b)=gcd(a,b-a),根据题意,让lcm最小那么就是要求最大的gcd,最大的gcd必定是两数中最大的约数,由于题目中b-a是定值,所以就可以枚举b-a的约数,然后把a凑到含有此约数为止,因此需要凑的值k=x-a%x,当然,a%x=0时k=0.除此之外记得开ll。

#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; const int maxn=1e5+5; ll n,m,a,b; vector<int> v; ll gcd(ll x,ll y) { return y==0 ? x: gcd(y,x%y); } ll lcm(ll x,ll y) { return x*y/gcd(x,y); } int main() { cin>>a>>b; if(a>b) { swap(a,b); } ll s=b-a; for(int i=1; i*i<=s; i++) { if(s%i==0) { v.push_back(i); if(i*i!=s) v.push_back(s/i); } } ll ans=1e18+5,k; for(int i=0; i<v.size(); i++) { ll t=0,x=v[i]; if(a%x!=0) { t=x-a%x; } ll temp=lcm(a+t,b+t); if(ans>temp) { ans=temp; k=t; } } if(a==b) k=0; cout<<k<<endl; return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律