Let's name a pair of positive integers (x,y) lucky if the greatest common divisor of them is equal to 11 (gcd(x,y)=1).
Let's define a chain induced by (x,y) as a sequence of pairs (x,y), (x+1,y+1), (x+2,y+2), ……, (x+k,y+k) for some integer k≥0. The length of the chain is the number of pairs it consists of, or (k+1).
Let's name such chain lucky if all pairs in the chain are lucky.
You are given n pairs (xi,yi). Calculate for each pair the length of the longest lucky chain induced by this pair. Note that if (xi,yi) is not lucky itself, the chain will have the length 00.
Input
The first line contains a single integer n (1≤n≤106) — the number of pairs.
Next n lines contains n pairs — one per line. The i-th line contains two integers xi and yi (1≤xi<yi≤107) — the corresponding pair.
Output
Print n integers, where the i-th integer is the length of the longest lucky chain induced by (xi,yi) or −1 if the chain can be infinitely long.
Example
input
Copy
4
5 15
13 37
8 9
10009 20000
output
Copy
0
1
-1
79
Note
In the first test case, gcd(5,15)=5>1, so it's already not lucky, so the length of the lucky chain is 0.
In the second test case, gcd(13+1,37+1)=gcd(14,38)=2. So, the lucky chain consists of the single pair (13,37).
思路: 因为gcd (x , y) == gcd (x , abs (x - y))
所以gcd (x + k , y + k) == gcd (x + k, abs (x - y))
所以令 ans = abs (x - y),我们需要找到最小 k ,使 gcd (x + k, ans) != 1 即可。
然后用欧拉筛把质数求出来,然后求出ans的质因子,判断到这个质因子的值最小要多少
代码
#include <bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
using namespace std;
#define x first
#define y second
#define NO cout << "NO" << '\n';
#define YES cout << "YES" << '\n';
#define long long
const int N = 1e7 + 10;
bool st[N];
int f[N],cc = 1;
void init()
{
for(int i = 2;i <= N;i ++)
{
if(!st[i])
f[cc++] = i;
for(int j = 1;f[j]*i<=N;j++)
{
st[f[j]*i] = true;
if(i%f[j] == 0)
break;
}
}
}
int n;
void solve()
{
int a,b;
cin >> a >> b;
int ca = abs(a-b);
if(__gcd(a,b) != 1)
{
cout << 0 << '\n';
return ;
}
if(ca == 1)
{
cout << -1 << '\n';
return ;
}
int ans = ca-a%ca;
//cout << ans << '\n';
//set<int>se;
int i = 1;
while(f[i]*f[i]<=ca)
{
if(ca%f[i] == 0)
{
int num = a%f[i];
ans = min(ans,(f[i]-num));
int x = ca/f[i];
if(!st[x])
{
ans = min(ans,(x-a%x));
}
ca/=f[i];
}
else
i ++;
}
cout << ans << '\n';
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
init();
int _ = 1;
cin >> _;
while (_ --) solve();
return 0;
}