[CF1748D] ConstructOR
题目描述
You are given three integers , , and . Your task is to find any integer which satisfies all of the following conditions, or determine that no such integers exist:
- ;
- is divisible by ;
- is divisible by .
输入格式
Each test contains multiple test cases. The first line of input contains one integer ( ) — the number of test cases.
Each test case consists of one line, containing three integers , , and ( ).
输出格式
For each test case print one integer. If there exists an integer which satisfies all of the conditions from the statement, print . Otherwise, print .
If there are multiple solutions, you may print any of them.
样例 #1
样例输入 #1
8
12 39 5
6 8 14
100 200 200
3 4 6
2 2 2
18 27 3
420 666 69
987654321 123456789 999999999
样例输出 #1
18
14
-1
-1
0
11
25599
184470016815529983
提示
In the first test case, is one of the possible solutions, since and , both of which are multiples of .
In the second test case, is one of the possible solutions, since , which is a multiple of .
In the third and fourth test cases, we can show that there are no solutions.
注意,后面的 都是代表按位或,而不是整除。
要让 是 的倍数,让 是 的倍数。要同时让两个数满足不好写,所以尝试让 ,并让 位 的倍数。
为什么敢于放到这一步呢?其实发现 的取值范围很大,所以极有可能达到这个条件。要满足上面这个条件,不妨让 的后 30 位就是 就行了
换句话说,
如果把 表示为 ,那么就是 ,拿个exgcd 就好了。exgcd 的解是肯定符合要求的,同时如果 exgcd 无解,肯定原来也无解。
但是有一个更简单的方法。
原方程有解的条件是 能整除 ,而 就是 ,那么可以通过不断除以 2 来判断。最后如果有解的时候, 的最后一位已经被除成 1 了。现在假设答案 满足了前 位与 相等,但是第 位与 不等,那么可以让 加上 。那么此时答案的这一位会发生变化,然后一直弄到 已经全部被模仿出来。
由于 ,解合法。
#include<bits/stdc++.h>
using namespace std;
int a,b,d,t,p,cnt;
long long ret;
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&a,&b,&d);
a|=b,p=1<<30,ret=cnt=0;
while(!(d&1)&&!(a&1))
a>>=1,d>>=1,p>>=1,++cnt;
if(!(d&1))
{
printf("-1\n");
continue;
}
// printf("%d %d %d\n",a,d,p);
for(int i=0;(1LL<<i)<=p&&(1LL<<i)<=a;i++)
{
if((ret>>i&1)!=(a>>i&1))
ret+=(1LL*d)<<i;
// printf("%d\n",ret);
}
printf("%lld\n",ret*(1LL<<cnt));
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】