Skip to content

Instantly share code, notes, and snippets.

@GnsP
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save GnsP/cfc9630961546cee8147 to your computer and use it in GitHub Desktop.

Select an option

Save GnsP/cfc9630961546cee8147 to your computer and use it in GitHub Desktop.
SUBARRAY GCD
#include <iostream>
using namespace std;
long long gcd(long long a, long long b){ // Find the GCD of two numbers using euclidian algorithm
if(b==0) return a;
return gcd(b, a%b);
}
int main(){
long long T, N, x, g;
cin >> T;
while(T--){
cin >> N;
g = 0; // This is initialised to 0 because gcd(0, anything) = anything
for(long long i=0; i<N; i++){ // Find GCD of the array of numbers using the property that gcd(a,b,c) = gcd(a, gcd(b,c))
cin >> x;
g = gcd(g, x);
}
if(g==1) cout << N << endl; // if gcd==1, then it's always 1 for the whole array
else cout << -1 << endl; // else no such subarray with gcd==1 exists
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment