B - Geometric Sequence Editorial by en_translator
\(A\) is a geometric progression if and only if
the ratios of adjacent terms, \(\frac{A_{i+1}}{A_i}\) \((1\leq i\leq N-1)\), are all equal;
this is equivalent to that
\[ \frac{A_{i+1}}{A_{i}}=\frac{A_{i+2}}{A_{i+1}} \]
holds for all \(1\leq i\leq N-2\).
However, this requires to compare fractions without errors.
Instead, we can even deform the equation as
\[ A_{i+1}^2=A_{i}A_{i+2} \]
to boil it down to comparisons of integers.
This can be implement with for
and if
statements.
Note that the terms \(A_i,A_{i+1},A_{i+2}\) are positive integers not exceeding \(10^9\), so the both hand sides do not exceed \(10^{18}\), which can be represented with \(64\)-bit integer types.
Note that using \(32\)-bit integer types like int
in C++ causes overflows.
Sample code in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
long long a[100];
bool flag=true;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<(n-2);i++){
if((a[i]*a[i+2])!=(a[i+1]*a[i+1]))flag=false;
}
if(flag)cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
posted:
last update: