1459C. Row GCD(经典数论)

2 篇文章 0 订阅
1 篇文章 0 订阅

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

题意:题目中有m次询问,每次要求出n个数加上一个数之后,这n个数的gcd。

分析:此题用到了gcd的更相减损术gcd(a,b)=gcd(a,b−a);gcd(a,b,c) = gcd(a,b-a,c-b)那么推广到这个数组,gcd(a1+bj,…,an+bj)=gcd(a1+bj,a2-a1,a3-a2,…,an-a(n-1))。所以我们只需先求出g=gcd(a2-a1,a3-a2,…)。而最终答案就是gcd(g,a1+bj);

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;
long long int a[200005],b[200005];
long long int c[200005];
int main()
{
    int n,m;
    while(~scanf("%d %d",&n,&m)){
        for(int i=0;i<n;i++){
            scanf("%lld",&a[i]);
            if(i==0)continue;
            c[i]=a[i]-a[i-1];
        }
        long long int ans=c[1];
        for(int i=1;i<n;i++)ans=__gcd(ans,c[i]);
        for(int j=0;j<m;j++){
            scanf("%lld",&b[j]);
            cout<<abs(__gcd(ans,b[j]+a[0]))<<" ";
        }
        cout<<endl;
    }
    return 0;
}

相关题目
也是与gcd更相减损有关的题

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

a碟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值