I would like to write a function in MATLAB that can quickly determine whether an array is coprime. Formally, we say that an N x 1 array x
is coprime if the largest positive integer that divides all N elements is 1 (see here for a more extensive definition).
The function that I have in mind should input an array of integers x
, and output true
if x is coprime. Some examples:
%example
x = [6,10,15];
iscoprime(x)
> true
%counter-example
x = 2*[1,2,3];
iscoprime(x)
> false
Answer The current best attempt at this is:
function value = iscoprime(x)
%remove 0 and take absolute value
x = abs(x(x==0));
nx = length(x);
%return true if all original entries = 0
if nx == 0, value = true;
%return false if x only contains 1 value and it is not 1
elseif nx == 1 & x~=1, value = false;
%return true if x contains a 1 (easy way to tell if x is coprime)
elseif any(x==1), value = true;
%check if x is coprime (based on Yasen's answer)
else
v = x(1);
for i = 2:nx
v = gcd(v,x(i));
if (v == 1),
value = true;
break
end
end
value = false;
end
end
Can anyone suggest a faster method?
You can use the built in MATLAB function for finding the Greatest Common Divisor (GCD) for every two consecutive numbers in the array and accumulate the result in some variable GCD. If GCD = 1, then the numbers are coprime. Otherwise, they are not coprime and GCD is their common factor.
Here is the code:
function GCD = iscoprime(x) % assuming x is an array,
GCD = x(1); % returning greatest common divisor for the array
for i=1:size(x, 2)
GCD = gcd(GCD, x(i));
end
end