题目链接:https://codeforc.es/contest/1459/problem/C
You are given two positive integer sequences a1,…,an and b1,…,bm. For each j=1,…,m find the greatest common divisor of a1+bj,…,an+bj.
Input
The first line contains two integers n and m (1≤n,m≤2⋅105).
The second line contains n integers a1,…,an (1≤ai≤1018).
The third line contains m integers b1,…,bm (1≤bj≤1018).
Output
Print m integers. The j-th of them should be equal to GCD(a1+bj,…,an+bj).
Example
input
4 4
1 25 121 169
1 2 7 23
output
2 3 8 24
分析
根据规律可得到:
gcd(a,b,c) = gcd(a,b-a,c-b)
即
gcd(a1, a2, a3, a4…) = gcd(a1, a2-a1, a3-a2, a4-a3…)
那么 a 数列都加上 bi 以后的最大公因数为:
gcd(a1-bi, a2-a1, a3-a2, a4-a3…)
所以我i们只要先算出 a2-a1, a3-a2, a4-a3… 的 gcd ,设为 x ,然后再计算 gcd(a1-bi, x) 即可得到答案。
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,m;
ll a[200007],b[200007];
int main()
{
scanf("%lld%lld",&n,&m);
for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
for(int i=1;i<=m;i++) scanf("%lld",&b[i]);
if(n == 1) for(int i=1;i<=m;i++) printf("%lld ",a[1] + b[i]);
else
{
ll diff = abs(a[1] - a[2]);
for(int i=2;i<n;i++) diff = __gcd(diff, abs(a[i] - a[i + 1]));
for(int i=1;i<=m;i++) printf("%lld ",__gcd(diff, a[1] + b[i]));
}
return 0;
}