题目:
Let's name a pair of positive integers(x,y) lucky if the greatest common divisor of them is equal to 1 (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≤10^6) — 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.
Sample 1
Inputcopy | Outputcopy |
---|---|
4 5 15 13 37 8 9 10009 20000 | 0 1 -1 79 |
Note
In the first test case, gcd(5,15)=5>1gcd(5,15)=5>1, so it's already not lucky, so the length of the lucky chain is 00.
In the second test case, gcd(13+1,37+1)=gcd(14,38)=2gcd(13+1,37+1)=gcd(14,38)=2. So, the lucky chain consists of the single pair (13,37)(13,37).
思路:
首先预处理得出小于10^7的所有数的最小质因子和所有质数,对于每个x,y,若gcd(x,y) > 1则输出0;若y-x的质因子个数为0,则输出-1,对于其他情况,零ans = inf,对y-x的所有质因子进行ans = min(ans,h[i] - x % h[i]),输出ans;
代码:
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 1e7 + 5;
int prime[N],mi[N],cnt;// mi[i] 表示i的最小质因子
bool vis[N];
int gcd(int a,int b){
return b == 0 ? a : gcd(b,a%b);
}
void getprime()
{
int n = N - 1;
for (int i = 2; i <= n; i++)
{
if (!vis[i]) {
prime[cnt++] = i;
mi[i] = i;
}
for (int j = 0; prime[j] <= n / i; j++)
{
vis[prime[j] * i] = true;
mi[prime[j] * i] = prime[j];
if (i % prime[j] == 0) break;
}
}
}
vector<int> fj(int a)
{
vector<int> v;
while (a != 1)
{
int p = mi[a];
while(a % p == 0)
{
a /= p;
}
v.push_back(p);
}
return v;
}
int main()
{
getprime();
int _;
cin >> _;
while(_--)
{
int x,y;
scanf("%d%d",&x,&y);
int ans = 1e9;
int o = y - x;
if (gcd(x,y)>1)
{
printf("0\n");
}
else
{
vector<int> h = fj(o);
if(h.size() == 0)
{
printf("-1\n");
}
else
{
for (int i = 0; i < h.size(); i++)
{
ans = min(ans,h[i] - x % h[i]);
}
printf("%d\n",ans);
}
}
}
return 0;
}