B. Playing with GCD

B. Playing with GCD

You are given an integer array a of length n.

Does there exist an array b consisting of n+1 positive integers such that ai=gcd(bi,bi+1) for all i (1in)?

Note that gcd(x,y) denotes the greatest common divisor (GCD) of integers x and y.

Input

Each test contains multiple test cases. The first line contains the number of test cases t (1t105). Description of the test cases follows.

The first line of each test case contains an integer n (1n105) — the length of the array a.

The second line of each test case contains n space-separated integers a1,a2,,an representing the array a (1ai104).

It is guaranteed that the sum of n over all test cases does not exceed 105.

Output

For each test case, output "YES" if such b exists, otherwise output "NO". You can print each letter in any case (upper or lower).

Example

input

复制代码
4
1
343
2
4 2
3
4 2 4
4
1 1 1 1
复制代码

output

YES
YES
NO
YES

Note

In the first test case, we can take b=[343,343].

In the second test case, one possibility for b is b=[12,8,6].

In the third test case, it can be proved that there does not exist any array b that fulfills all the conditions.

 

解题思路

  比赛的时候想了快一个小时都没想到怎么做。关键就是在于根据已有的数组a去构造出数组b

  对于ai,有ai1=gcd(bi1,bi)ai=gcd(bi,bi+1),可以发现bi既是ai1的倍数,也是ai的倍数,即满足bi%ai1=0,bi%ai=0,因此bi就是ai1ai的公倍数。但这里我们取bi=lcm(ai1,ai),这是因为如果bi取最小公倍数的倍数的话,即k×lcm(ai1,ai)k是大于1的整数,那么就有gcd(bi,bi+1)=gcd(ki×lcm(ai1,ai),ki+1×lcm(ai,ai+1))  gcd(lcm(ai1,ai),lcm(ai,ai+1))=ai

  即对于任意的bi如果不是取lcm(ai1,ai),那么经过求gcd操作后得到的不一定是原来的a数组(跟确切的意思是,如果每一个bi都满足bi=lcm(ai1,ai),且经过gcd操作后可以得到a数组,那么如果b的构造方式为bi=ki×lcm(ai1,ai),此时经过gcd操作后就不一定可以得到a数组,因为得到的结果可能是原来位置上的数的倍数)。

  当然,如果i=1,那么b1=a1;如果i=n,那么bn+1=an

  最后还要判断构造得到的b数组经过gcd操作后能否得到a数组,如果发现gcd(bi,bi+1)ai,那么就不存在解。

  AC代码如下:

复制代码
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int N = 1e5 + 10;
 5 
 6 int a[N], b[N];
 7 
 8 int gcd(int a, int b) {
 9     return b ? gcd(b, a % b) : a;
10 }
11 
12 void solve() {
13     int n;
14     scanf("%d", &n);
15     for (int i = 0; i < n; i++) {
16         scanf("%d", a + i);
17     }
18     b[0] = a[0], b[n] = a[n - 1];
19     for (int i = 1; i < n; i++) {
20         b[i] = a[i] / gcd(a[i], a[i - 1]) * a[i - 1]; // lcm(a[i], a[i - 1])
21     }
22     for (int i = 0; i < n; i++) {
23         if (gcd(b[i], b[i + 1]) != a[i]) {
24             printf("NO\n");
25             return;
26         }
27     }
28     printf("YES\n");
29 }
30 
31 int main() {
32     int t;
33     scanf("%d", &t);
34     while (t--) {
35         solve();
36     }
37     
38     return 0;
39 }
复制代码

 

参考资料

  Codeforces Round #825 (Div. 2) Editorial:https://codeforces.com/contest/1736

posted @   onlyblues  阅读(253)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
Web Analytics
点击右上角即可分享
微信分享提示