There are several questions on Stack Overflow discussing how to find the Greatest Common Divisor of two values. One good answer shows a neat recursive function
int GCD(int a,int b){ return (!b) ? (a) : GCD(b, a%b); } void calc(a){ int gcd = a[0]; for(int i = 1 ; i < n;i++){ if(gcd == 1){ break; } gcd = GCD(gcd,a[i]); } }