Codeforces Round #691 (Div. 2) C. Row GCD

题目链接: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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值