Codeforces CF1459C. Row GCD C++ GCD分配率

博客围绕求解两个正整数序列相关的最大公约数问题展开。给定序列a和b,需对b中每个元素,求a中各元素加上该元素后的最大公约数。通过最大公约数分配律,可先求数组a的最大公约数g,再求GCD(a1+bj, g)得出结果。

C. Row GCD

time limit per test2 seconds
memory limit per test512 megabytes
inputstandard input
outputstandard output
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
inputCopy

4 4
1 25 121 169
1 2 7 23

outputCopy

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[]数字加上bj后,等价变形发现答案为GCD(a1+bj,a2-a1, a3-a2, a4-a3…),
只需要先求出数组a[]的最大公约数g,之后求出GCD(a1+bj,g)即可。

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 2e5 + 10;
ll a[N], b[N];
ll gcd(ll a,ll b)
{
	return b?gcd(b,a%b):a;
}
int main() {
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) cin >> a[i];
    for (int i = 1; i <= m; ++i) cin >> b[i];

    ll g = 0;
    for (int i = 2; i <=n; ++i) {
        g = gcd(g, a[i] - a[i - 1]);
	}

    for (int i = 1; i <=m; ++i) {
        cout << abs(gcd(a[1] + b[i], g)) << " ";
    }
    puts("");

    return 0;
}



评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Jay_fearless

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

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

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

打赏作者

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

抵扣说明:

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

余额充值