C Collatz Conjecture
In 1978 AD the great Sir Isaac Newton, whilst proving that Pis a strict superset of N P, defined the Beta Alpha Pi Zetafunction f as follows over any sequence of positive integersa1, . . . , an. Given integers 1 ≤ i ≤ j ≤ n, we define f(i, j)as gcd(ai, ai+1, . . . , aj−1, aj ).
About a century later Lothar Collatz applied this function tothe sequence 1, 1, 1, . . . , 1, and observed that f always equalled1. Based on this, he conjectured that f is always a constantfunction, no matter what the sequence aiis. This conjecture, now widely known as theCollatz Conjecture, is one of the major open problems in botanical studies. (The StrongCollatz Conjecture claims that however many values f takes on, the real part is always 12.)
You, a budding young cultural anthropologist, have decided to disprove this conjecture. Givena sequence ai, calculate how many different values f takes on.
Input
The input consists of two lines.
• A single integer 1 ≤ n ≤ 5 · 105, the length of the sequence.
• The sequence a1, a2, . . . , an. It is given that 1 ≤ ai ≤ 1018.
Output
Output a single line containing a single integer, the number of distinct values f takes on overthe given sequence.
思路:计算每个以i结尾的子串的gcd。每次用in[]记录,若gcd不重复加入到s[]中。最后去重。
代码:
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
LL in[1000010]; //前i位最大公约数
LL s[10000010];
//枚举右端点,找出以i结尾之前所有不同的gcd,ans记录出现过的不同的gcd。
LL gcd(LL a,LL b)
{
return a==0?b:gcd(b%a,a);
}
int main()
{
int n;
LL x;
cin>>n;
int top=0;
int k=0;
for(int i=0;i<n;i++)
{
cin>>x;
for(int j=0;j<top;j++) //求以x结尾的gcd
{
LL y=gcd(x,in[j]); //a1a2最大公约数in[j],求a1a2a3就是求gcd(a3,in[j])
if(y!=in[j])
{
s[k++]=in[j];
in[j]=y;
}
}
in[top++]=x;
top=unique(in,in+top)-in; //去重
}
for(int i=0;i<top;i++)
s[k++]=in[i];
sort(s,s+k);
cout<<unique(s,s+k)-s<<endl;
return 0;
}